简体   繁体   English

使用 for 循环在同一个工作簿中写入多个工作表

[英]Writing multiple sheets in same workbook using for loop

Scenario:设想:

  1. Read an excel file with multiple sheets读取包含多个工作表的 excel 文件
  2. For each sheet at input read a few specific columns and manipulate the existing data对于输入的每个工作表,读取一些特定的列并操作现有数据
  3. Create an output dataframe创建一个 output dataframe
  4. Save this dataframe in one existing output file as a new sheet将这个 dataframe 保存在一个现有的 output 文件中作为一个新工作表

Below is the snippet of my code:下面是我的代码片段:

for sheet in all_sheets: # all_sheets is the list of sheets from the input file
    print(sheet) # Here i transform the data but removed the 
    writer = pd.ExcelWriter('Output.xlsx', engine='xlsxwriter')
    df_final_4.to_excel(writer, sheet_name=sheet, index=True)
    writer.save()

Problem Statement:问题陈述:

  1. The file is written with only one sheet which contains the data for the last iteration.该文件只用一张纸写入,其中包含最后一次迭代的数据。
  2. The previous iteration gets overwritten and only one sheet remains in the output file.之前的迭代被覆盖,output 文件中只剩下一张纸。
  3. I have tried multiple approches but each yeild the same result.我尝试了多种方法,但每种方法都产生了相同的结果。

Can anyone please guide me where i am going wrong?谁能指导我哪里出错了?

Other approches:其他方法:

for sheet in all_sheets:
    writer = pd.ExcelWriter('Output.xlsx', engine='xlsxwriter')
    df_final_4.to_excel(writer, sheet_name=sheet, encoding='utf-8', index=True)
    writer.save()

for sheet in all_sheets[8:10]:
    print(sheet)
    writer = pd.ExcelWriter('newfile.xlsx', engine='xlsxwriter')
    df_final_4.to_excel(writer, sheet_name=sheet, index=True)
    writer.save()

wb = openpyxl.Workbook()
wb.save('Output.xlsx')
book = load_workbook('Output.xlsx')
writer = pd.ExcelWriter('Output.xlsx', engine='openpyxl') 
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df_final_4.to_excel(writer, sheet, index=True)
writer.save()
writer.close()
    

I was able to solve the issue by changing the sequence of the code:我能够通过更改代码的顺序来解决问题:

writer = ExcelWriter('Output.xlsx')
for sheet in all_sheets:
    <do calculations>
    <do manipulations>
    <do slicing>
    
    df.to_excel(writer, sheet_name=sheet)
writer.save()

This is basically because we want to write multiple sheets in the same file so the initialization or definition of the writer should be only done once.这基本上是因为我们想在同一个文件中写入多个工作表,所以编写器的初始化或定义应该只进行一次。

However, in case, only one sheet is required to be written then the writer can be defined anywhere inside the loop.但是,如果只需要写入一张表,则可以在循环内的任何位置定义编写器。

I managed to solve this using dictionaries.我设法用字典解决了这个问题。 create a dictionary with basic keys and the below code hellped:创建一个带有基本键的字典,下面的代码帮助了:

df_dict = {}
for i in range(len(df)):
    df_dict[i] =  df[i]
writer = pd.ExcelWriter(path,engine = 'xlsxwriter')

for name,value in df_dict.items():
    value.to_excel(writer,sheet_name = 'x'+str(name))
    print("sheet {} written".format(name))

writer.save()

this created new sheets with the multiple dataframes.这创建了包含多个数据框的新工作表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python pyexcelerate 库将多个工作表写入同一个工作簿? - Python pyexcelerate library writing multiple sheets to same workbook? Python / Pandas:使用“for-loop”将多个Dataframes写入Excel工作表 - Python/Pandas: writing multiple Dataframes to Excel sheets using a “for-loop” 使用 python 循环在一个 excel 工作簿中创建多个 excel 工作表,从一个 Z6A8064B5DF4794555500553C7 - Using python loop to create multiple excel sheets in one excel workbook from one dataframe 使用 pandas 从同一工作簿中的多个 excel 工作表中提取部分数据 - Extract Partial Data from multiple excel sheets in the same workbook using pandas 将多个 excel 工作表写入一个循环代码 - writing multiple excel sheets into one for loop code 如何使用openpyxl在同一工作簿中同时写两张纸 - How to write two sheets in a single workbook at the same time using openpyxl 使用 Pandas 将 Excel 工作簿的多张工作表放入不同的数据框中 - Multiple sheets of an Excel workbook into different dataframes using Pandas 合并多个工作簿和工作表时出错 - Error with combining multiple workbook and sheets 当第一列在工作簿中的名称不同时,如何使用 Python 在单个工作簿中合并多个工作表 - How to merge multiple sheets in a single workbook using Python when the first column is named differently across the workbook 将工作簿从一个工作簿循环移动到另一个工作簿 - Move sheets from one workbook to another in a loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM