Creating a blank worksheet and adding text to that new worksheet using Python, ExcelWriter and openpyxl

无人久伴 提交于 2020-03-25 17:54:50

问题


I'm creating a new excel workbook using ExcelWriter with the openpyxl engine. I am able to export dataframes which as a side effect create a new worksheet, but when I try to add

  • a new blank workbook I get the error ("workbook is not defined")
  • Text to a cell in an existing workbook I get the error ("'Summary_Data' is not defined ")

How would I modify this code below to a) add a new blank worksheet b) add text to a specific cell in a specific worksheet

I'm probably getting confused by trying to mix and match various snippet of code from various places.

    #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()


回答1:


Use writer.book to access the underlying openpyxl workbook object, followed by book.create_sheet() to initialize a new openpyxl worksheet object:

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()


来源:https://stackoverflow.com/questions/58453420/creating-a-blank-worksheet-and-adding-text-to-that-new-worksheet-using-python-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!