简体   繁体   中英

How can I embed Python Codes into Excel(Xlwings) and how can everyone use it?

There are a few issues I am wonder about xlwings module and need your help.

The code I am working on, is briefly working on a database creation by entering the data I enter on one sheet row by row in the date_range specified on the other sheet.

My Input sheet pic.: enter image description here

My Output Sheet pic.: enter image description here

import pandas as pd
import xlwings as xw

def world():

import os
script_dir = os.path.dirname(__file__)  
rel_path = "database.xlsm"
file_path = os.path.join(script_dir, rel_path)

wb = xw.Book(file_path)

wb.save()

ws = wb.sheets["Sheet1"]
ws2 = wb.sheets["Sheet2"]

df = pd.read_excel(file_path)
area=df["B"].loc[0]
country=df["B"].loc[1]
city=df["B"].loc[2]
firstdate=df["B"].loc[3]
lastdate=df["B"].loc[4]

daterange=pd.date_range(firstdate,lastdate)
a = ws2.range('A' + str(ws2.cells.last_cell.row)).end('up').row + 1

for i in daterange:
    ws2.cells(a,1).value=area.upper()
    ws2.cells(a,2).value=country.upper()
    ws2.cells(a,3).value=city.upper()
    ws2.cells(a,4).value=i
    a+=1

wb.sheets['Sheet2'].autofit()

With the code I wrote by using pandas, I can run the program on my own computer.When I click "RUN" button on Excel File, it fills 'Sheet2' as I want(shown above Output pic.).

My questions are how can I embed this code that I wrote using pandas, into Excel? And how do I convert it to a format that everyone can use (including other computers without pandas or xlwings)?

Thanks in advance.

I don't know if is possible do what you want. I know that LibreOffice Calc can call python scripts, but I dont know about their limitations or how you can import pandas.

I suggest you to recreate your code using VBA, considering that your code is simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM