我正在尝试在电子表格中插入按钮,但是无法正确使用insert_button。
我到目前为止所做的:
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
workbook = writer.book
df_tst.to_excel(writer, sheet_name='Info' ,index = False , header = False)
workbook.add_vba_project(r'C:\Users\...\Project.bin')
workbook.filename = 'test.xlsm'
writer.save()
但是我无法在电子表格“ Info”中使用insert_button(可能是因为我尝试使用错误的方式...)
然后我尝试了一个到目前为止可以按预期工作的其他选项,但是我要尝试的是插入一个按钮,如下所示:
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
workbook = writer.book
worksheet1 = workbook.add_worksheet()
worksheet1.write('A1', 'TEST.')
worksheet1.insert_button('C6', {'macro': 'macro_test',
'caption': 'Macro Test',
'width': 100,
'height': 80})
workbook.add_vba_project(r'C:\Users\...\Project.bin')
workbook.filename = 'test.xlsm'
writer.save()
问题是,使用“ worksheet1 = workbook.add_worksheet()”时,我无法将数据框插入到工作表中,尝试时出现以下错误:
worksheet1.write(df_tst)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
worksheet1.write(df_tst)
File "C:\Users\...\worksheet.py", line 63, in cell_wrapper
int(first_arg)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DataFrame'
因此,将数据框内容插入使用“ workbook.add_worksheet()”创建的工作表中,或使用“ insert_button”插入df.to_excel创建的电子表格中,即可解决问题。
预先感谢
答案 0 :(得分:0)
尝试使用xlsxwriter直接打开文件,而不是熊猫包装器
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet1 = workbook.add_worksheet()
worksheet1.write('A1', 'TEST.')
worksheet1.insert_button('C6', {'macro': 'macro_test',
'caption': 'Macro Test',
'width': 100,
'height': 80})
workbook.add_vba_project(r'C:\Users\...\Project.bin')
workbook.filename = 'test.xlsm'
writer.save()
答案 1 :(得分:0)
这是Pandas和XlsxWriter的有效示例。另请参见XlsxWriter文档中的Working with Python Pandas and XlsxWriter。
import os
import pandas as pd
import xlsxwriter
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.set_column('D:D', 30)
# Add the VBA project binary.
workbook.add_vba_project('./vbaProject.bin')
# Show text for the end user.
worksheet.write('D3', 'Press the button to say hello.')
# Add a button tied to a macro in the VBA project.
worksheet.insert_button('D5', {'macro': 'say_hello',
'caption': 'Press Me',
'width': 80,
'height': 30})
# Close the Pandas Excel writer and output the Excel file.
writer.save()
# Pandas doesn't allow a '.xslm' extension but Excel requires
# it for files containing macros so we rename the file.
os.rename('pandas_simple.xlsx', 'pandas_simple.xlsm')
输出: