简体   繁体   English

如何将 Python 代码嵌入 Excel(Xlwings) 以及每个人如何使用它?

[英]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.我对 xlwings 模块有一些疑问,需要您的帮助。

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.我正在处理的代码是通过在另一张纸上指定的 date_range 中逐行输入我在一张纸上输入的数据来简要创建数据库。

My Input sheet pic.: enter image description here我的输入表图片:在此处输入图像描述

My Output Sheet pic.: enter image description here我的 Output 工作表图片:在此处输入图片描述

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.).使用我使用 pandas 编写的代码,我可以在自己的计算机上运行该程序。当我单击 Excel 文件上的“运行”按钮时,它会根据需要填充“Sheet2”(如 Z29C2C02A361C9D70258Z7 上方所示)。

My questions are how can I embed this code that I wrote using pandas, into Excel?我的问题是如何将我使用 pandas 编写的代码嵌入到 Excel 中? And how do I convert it to a format that everyone can use (including other computers without pandas or xlwings)?以及如何将其转换为每个人都可以使用的格式(包括其他没有 pandas 或 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.我知道 LibreOffice Calc 可以调用 python 脚本,但我不知道它们的限制或如何导入 pandas。

I suggest you to recreate your code using VBA, considering that your code is simple.考虑到您的代码很简单,我建议您使用 VBA 重新创建您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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