Loop for writing in every sheet without erasing the previous data - EDIT

76 Views Asked by At

I have an ordereddict which I achieved to transfer to a new excel file with multiple keys. Each key of it corresponds to a sheet in the excel file. I would like to code a loop that allows me to write on the A1 position of all the sheets in my file.

  • The code below writes my ordereddict in a new excel file:

# Importing modules
import openpyxl as op
import pandas as pd
import numpy as np
import xlsxwriter
from openpyxl import Workbook, load_workbook

# Defining my file
my_file = r'\machukovich\Desktop\stack.xlsx'

# Loading the file into a dictionary of Dataframes
dfs_my_file = pd.read_excel(my_file, sheet_name=None, skiprows=2)

# The path of the new file I wish to write on
my_new_path = r'\machukovich\Desktop\new.xlsx'

# At this point I have made a few modifications in dfs_my_file which are non important to the core of this question.

# Create a Pandas Excel writer using XlsxWriter as the engine.

with pd.ExcelWriter(my_new_path, engine="xlsxwriter") as writer:
    for sheet_name, df in dfs_my_file.items():
            df.to_excel(writer, sheet_name=sheet_name, startrow=6, index=False)

# Close the Pandas Excel writer and output the Excel file.
writer.close()    
writer.save()

  • My dataset for dfs_my_file (the ordered dictionary):

{'Sheet_1':     ID      Name  Surname  Grade
 0  104  Eleanor     Rigby      6
 1  168  Barbara       Ann      8
 2  450    Polly   Cracker      7
 3   90   Little       Joe     10,
 'Sheet_2':     ID       Name   Surname  Grade
 0  106       Lucy       Sky      8
 1  128    Delilah  Gonzalez      5
 2  100  Christina   Rodwell      3
 3   40      Ziggy  Stardust      7,
 'Sheet_3':     ID   Name   Surname  Grade
 0   22   Lucy  Diamonds      9
 1   50  Grace     Kelly      7
 2  105    Uma   Thurman      7
 3   29   Lola      King      3}

  • I tried with the code below (I don't know how to write the string below in every sheet of my excel file):

# Defining workbook and worksheet

workbook = xlsxwriter.workbook
worksheet = writer.sheets[sheet_name]

# I tried with this iteration 

with pd.ExcelWriter(my_new_path, engine="xlsxwriter") as writer:
        for sheet_name, df in dfs_my_file():
            worksheet.write('A1', 'RANDOM TEXT 1')
            worksheet.write('A2', 'RANDOM TEXT 2')

  • But I end up with the error below, without understanding the origin of it.

KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18328/702301548.py in <module>
      1 workbook = xlsxwriter.workbook
----> 2 worksheet = writer.sheets[sheet_name]
      3 
      4 with pd.ExcelWriter(my_new_path, engine="xlsxwriter") as writer:
      5         for sheet_name, df in dfs_my_file():

KeyError: 'Sheet_1'

Has anyone experienced this error before? Could you help me writting my excel file? Regards.

0

There are 0 best solutions below