Search code examples
pythonexcelpandas.excelwriter

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


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


Solution

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