[英]Saving pandas dataframe subsets to xlsx using df.to_excel
[英]Insert Button to Spreadsheet using df.to_excel
我正在嘗試將按鈕插入電子表格中,但無法正確使用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創建的電子表格中都可以解決此問題。
提前致謝
嘗試使用xlsxwriter直接打開文件,而不是pandas包裝器
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()
這是Pandas和XlsxWriter的工作示例。 另請參閱XlsxWriter文檔中的使用Python Pandas和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')
輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.