Excel 使用 While 循环导出

Excel export using While loop

我是 Python 的新手。我正在研究一个大型分析程序,这是它的一个片段。现在,此代码段导出多个 excel 文件。是否可以在单个 excel 文档中保存每个循环在 sheet 上完成的操作?所以基本上现在,它导出 5 个文件,而不是导出 5 个单独的文件,我可以使用这个循环并导出 1 个文件,它有 5 sheets?

x = 0
y = 0
#these are empty variables for the while loop


#while loop that loops up to the system amount
#breaks up df into systems
#exports excel for each system
while x < int(SystemCount): 
    x += 1
    y += 1 
    System = minus4[minus4['System'] == "System " + str(y)]
    System.to_excel('U4Sys' +  str(y) + '.xlsx', sheet_name='sheet1', index=False)
    print(System.head())

末尾打印出这个

    email    System
test1@test.com  System 1
test2@test.com  System 1
test3@test.com  System 1
test4@test.com  System 1
test5@test.com  System 1

         email    System
test1@test.com  System 2
test2@test.com  System 2
test3@test.com  System 2
test4@test.com  System 2
test5@test.com  System 2

         email    System
test1@test.com  System 3
test2@test.com  System 3
test3@test.com  System 3
test4@test.com  System 3
test5@test.com  System 3

感谢您花时间阅读本文!

编辑(使用 pandasExcelWriter 计算 OP):

您需要使用 ExcelWriter 定义您的目标文件,然后使用变量 sheet 名称写入它。还为您的迭代提供一些 Python 清理:

#breaks up df into systems
#exports excel for each system

writer = ExcelWriter('U4SysOutput.xlsx')
for x in range(1, int(SystemCount)+1): 

    System = minus4[minus4['System'] == "System " + str(x)]
    System.to_excel(writer, sheet_name='sheet{}'.format(x), index=False)
    print(System.head())

您需要在 pandas.to_excel()

中使用 pandas.ExcelWriter()

这是您的过程的简化版本:

import numpy as np
import pandas as pd

# Output Excel file:
writer = pd.ExcelWriter("your_excel_filepath.xlsx")

# Your variables:
x, y = 0, 0

# The loop:             
while x < 5:

    x += 1
    y += 1 

    # The DataFrame for this iteration:
    df = pd.DataFrame(np.random.randn(5,4), columns=list("ABCD"))

    # Write the DataFrame to a new sheet:
    df.to_excel(writer, "sheet_{}".format(x))
writer.save()