使用XlsxWriter将数据框和按钮添加到同一工作表中

问题描述 投票:1回答:1

我能够创建一个excel文件,其中一张工作表中的数据帧中的数据,另一张工作表中的按钮可运行宏我需要的是使数据框中的数据都比同一张纸中的按钮都具有]

这是我发现我尝试修改的代码:

import pandas as pd
import xlsxwriter

df = pd.DataFrame({'Data': [10, 20, 30, 40]})

writer = pd.ExcelWriter('hellot.xlsx', engine='xlsxwriter')
worksheet = workbook.add_worksheet()
#df.to_excel(writer, sheet_name='Sheet1')

workbook  = writer.book
workbook.filename = 'test.xlsm'
worksheet = workbook.add_worksheet()
workbook.add_vba_project('./vbaProject.bin')

worksheet.write('A3', 'Press the button to say hello.')

#Add a button tied to a macro in the VBA project.
worksheet.insert_button('A1', {'macro':   'start',
                              'caption': 'Press Me',
                              'width':   80,
                              'height':  30})

df.to_excel(writer, sheet_name ='Sheet2') 

writer.save()


workbook.close()
pandas xlsxwriter
1个回答
1
投票

[我知道您只是问过如何在同一张纸上插入按钮,但我决定检查宏如何与xlsxwriter一起使用,因此我编写了有关如何添加宏的完整教程。

1]首先,我们需要手动创建一个包含宏的文件,以便将其提取为bin文件,并在以后使用xlsxwriter注入。因此,我们创建一个新的excel文件,转到“开发人员”选项卡,“ Visual Basic”,“插入模块”并编写以下代码:

Sub TestMsgBox()
    MsgBox "Hello World!"
End Sub

保存带有xlsm扩展名的文件以包含宏,例如如Book1.xlsm。

2)现在我们需要提取bin文件。打开您的cmd并浏览到保存Book1.xlsm的目录。然后,通过文件浏览器浏览到已安装python的文件夹(或虚拟环境文件夹),并搜索vba_extract.py。将此脚本复制到Book1.xlsm所在的文件夹中。然后输入cmd:

python vba_extract.py Book1.xlsm

这样,您将提取宏并在同一文件夹中创建vbaProject.bin文件。

3)现在是时候创建最终文件了。删除Book1.xlsm和vba_extract.py文件,因为它们不再需要,并运行以下代码:

import pandas as pd

# Create a test dataframe
df = pd.DataFrame({'Data': [10, 20, 30, 40]})

# Import it through the xlsxwriter
writer = pd.ExcelWriter('hello_world.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)

# Create the workbook and the worksheet
workbook = writer.book
workbook.filename = 'hello_world.xlsm' # rename the workbook to xlsm extension
worksheet = writer.sheets['Sheet1']

# Inject the bin file we extracted earlier
workbook.add_vba_project('./vbaProject.bin')

# Insert a description
worksheet.write('B1', 'Press the button to say hello.')

#Add a button tied to a macro in the VBA project.
worksheet.insert_button('B2', {'macro': 'TestMsgBox',
                              'caption': 'Press Me',
                              'width': 80, 'height':  30})

# Finally write the file
writer.save()

现在按钮与您的数据在同一工作表中,并且可以正常工作:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.