英文:
Python XLSXWriter: getting writer from workbook
问题
我正在尝试使用Pandas和xlsxwriter构建自动化生成Excel报告的方法。我将写入器传递给函数,以便能够添加工作表等内容。然后我将写入器返回,不可避免地被传递到另一个函数中,工作簿再次被提取出来。示例如下:
writer = pd.ExcelWriter(filename, engine="xlsxwriter")
df.to_excel(writer, sheet_name='first_sheet')
def test_func(excel_writer):
workbook = excel_writer.book
worksheet = workbook.add_worksheet('second_sheet')
# *在工作表上执行一些操作*
return excel_writer
writer = test_func(writer)
writer.close()
传入的数据框中已经包含数据,在函数中我对数据框进行一些格式化和添加更多数据。然而,保存的Excel文件是空的。我认为从函数返回写入器可能是问题的原因。任何帮助将不胜感激!
英文:
I am trying to build automation to build excel reports using Pandas and xlsxwriter. I pass the writer to functions to be able to add worksheets and etc. I then return the writer back, which inevitably gets passed into another function and the workbook is taken out again. Example as below
writer = pd.ExcelWriter(filename, engine="xlsxwriter")
df.to_excel(writer, sheet_name='first_sheet')
def test_func(excel_writer):
workbook = excel_writer.book
worksheet = workbook.add_worksheet('second_sheet')
*Do something with the worksheet*
return excel_writer
writer = test_func(writer)
writer.close()
The dataframe passed in has data in it already, within the function I do some formatting and adding of more data. However the excel file that saves is empty. My thought is that the return of the writer from the function is the issue. Any help would be appreciated!
答案1
得分: 1
df.to_excel()
不返回一个写入器。你需要自己实例化一个。
def test_func(excel_writer):
workbook = excel_writer.book
worksheet = workbook.add_worksheet("second_sheet")
# *在工作表上执行一些操作*
return excel_writer
# 使用上下文管理器在操作完成后自动关闭
with pd.ExcelWriter("sample.xlsx", engine="xlsxwriter") as writer:
df.to_excel(writer, sheet_name="first_sheet")
writer = test_func(writer)
英文:
df.to_excel()
does not return a writer. You need to instance one yourself.
def test_func(excel_writer):
workbook = excel_writer.book
worksheet = workbook.add_worksheet("second_sheet")
# *Do something with the worksheet*
return excel_writer
# Use with block to auto-close after operation is finished
with pd.ExcelWriter("sample.xlsx", engine="xlsxwriter") as writer:
df.to_excel(writer, sheet_name="first_sheet")
writer = test_func(writer)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论