【问题标题】:Excel export using While loop使用 While 循环导出 Excel
【发布时间】:2018-01-19 22:11:20
【问题描述】:

我是 Python 新手。我正在开发一个大型分析程序,这是它的一个 sn-p。现在,这个 sn-p 导出多个 excel 文件。是否可以将每个循环所做的事情保存在单个 Excel 文档中的工作表上?所以基本上现在,它导出 5 个文件,而不是导出 5 个单独的文件,我可以使用这个循环并导出 1 个文件,它有 5 张纸吗?

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

感谢您抽出宝贵时间阅读本文!

【问题讨论】:

  • 您使用什么库将其发送到 Excel?
  • 你试过 XlsxWriter 吗? xlsxwriter.readthedocs.io
  • 嘿抱歉,我正在使用 Pandas、ExcelWriter 和 ExcelFile

标签: python excel pandas while-loop export-to-excel


【解决方案1】:

编辑(使用pandasExcelWriter 考虑OP):

您需要使用ExcelWriter 定义您的目标文件,然后使用可变工作表名称写入它。还为您的迭代提供一些 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、ExcelWriter 和 Excel 文件。我尝试了上面的代码,它只是保存了循环的最后一次迭代。所以只有系统 5 被保存到 excel 中,而不是 1、2、3 或 4
  • 啊。在这种情况下,您有 stackoverflow.com/questions/14225676/… 的副本
【解决方案2】:

您需要在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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-08-03
    • 2017-06-03
    • 1970-01-01
    • 2012-01-02
    相关资源
    最近更新 更多