Python XLSXWriter: 从工作簿获取写入器

huangapple go评论59阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年3月10日 00:47:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定