问题描述
我有一个正在运行的 python 脚本,它当前执行三个独立的操作,并将每个结果输出到不同的 excel 文件.是否可以将我的所有输出都放在不同工作表上的一个 Excel 文件中?似乎最新的结果总是覆盖整个excel文件.
I have a python script I am running that currently does three separate things and outputs each result to a different excel file. Is it possible to instead have all of my outputs in one excel file on different sheets? It seems that the latest result always overwrites the whole excel file.
以下是我的想法:
df_finit1.to_excel('OutFile.xlsx', sheet_name = 'Sheet1')
df_finit2.to_excel('OutFile.xlsx', sheet_name = 'Sheet2')
df_finit3.to_excel('OutFile.xlsx', sheet_name = 'Sheet3')
我还尝试使用 xlsx writer 创建一个包含 3 个不同工作表的文件,然后输出到这些工作表,但得到了相同的结果.有小费吗?
I also tried to use xlsx writer to create a file with 3 different sheets, and output to those sheets but I got the same result. Any tips?
推荐答案
您应该使用 ExcelWriter
,它允许打开单个 .xlsx
文件并对其进行操作.
You should use ExcelWriter
, it allows to open single .xlsx
file and manupulate it.
import pandas as pd
# Initialize xlsx writer
writer = pd.ExcelWriter('output_file.xlsx', engine='xlsxwriter')
workbook = writer.book
df1 = pd.DataFrame({"a": [1,2,3],
"b": [1,2,3]})
df2 = pd.DataFrame({"c": [1,2,3],
"d": [1,2,3]})
df3 = pd.DataFrame({"e": [1,2,3],
"f": [1,2,3]})
df1.to_excel(writer,
sheet_name="sheet1",
startrow=0,
startcol=0)
df2.to_excel(writer,
sheet_name="sheet2",
startrow=0,
startcol=0)
df3.to_excel(writer,
sheet_name="sheet3",
startrow=0,
startcol=0)
writer.save()
这篇关于输出到excel文件而不覆盖工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!