0

我正在使用带有 openpyxl 引擎的 ExcelWriter 创建一个新的 excel 工作簿。我能够导出作为副作用创建新工作表的数据框,但是当我尝试添加

  • 一个新的空白工作簿我收到错误(“工作簿未定义”)
  • 向现有工作簿中的单元格发送文本我收到错误消息(“'Summary_Data' 未定义”)

我将如何将下面的代码修改为 a) 添加新的空白工作表 b) 将文本添加到特定工作表中的特定单元格

我可能会因为试图混合和匹配来自不同地方的各种代码片段而感到困惑。

    #export various dataframes to excel
    with pd.ExcelWriter(f"data validation for {FNum}_{FName}.xlsx",engine='openpyxl') as writer:

        DWoldfiltered.to_excel(writer,sheet_name="Previous_load")

        #An attempt to create a new blank worksheet which fails
        #worksheet1 = workbook.add_worksheet('Summary_Data')

        #this works as a way of creating a worksheet
        new_summary.to_excel(writer,sheet_name="Summary_Data",startrow=1,startcol=1)
        old_summary.to_excel(writer,sheet_name="Summary_Data",startrow=13,startcol=1)

        #two different attempts to a) reference the new workbook b) add text to specific cells,
        #which both fail
        Summary_Data.cell(0,1).value="Latest load summary"
        Summary_Data.write(0,0,"Latest load summary")

    writer.save()

4

1 回答 1

2

用于writer.book访问底层的 openpyxl 工作簿对象,然后book.create_sheet()初始化一个新的 openpyxl 工作表对象:

import pandas as pd
import pandas.util.testing as tm

# Create example dataframe
df = tm.makeDataFrame()

with pd.ExcelWriter("out.xlsx", engine='openpyxl') as writer:
    # Write dataframe to excel worksheet
    df.to_excel(writer, sheet_name="dataframe")

    # Create new empty worksheet
    # Note: `sheet` is a `openpyxl.worksheet.worksheet.Worksheet` object
    book = writer.book
    sheet = book.create_sheet("summary")

    # Write data to worksheet cells
    sheet.cell(1, 1).value = "Amount of dataframe rows:"
    sheet.cell(2, 1).value = df.shape[0]

writer.save()
于 2019-10-21T05:34:23.547 回答