[英]Writing multiple sheets in same workbook using for loop
Scenario:设想:
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:问题陈述:
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.