Python:在多个Excel工作表上打印输出

时间:2018-09-02 21:16:19

标签: python excel xlsxwriter

我有4个列表,每个列表都有33个值,并希望在excel中打印组合。 Excel将每个工作表中的行数限制为 1,048,576 ,并且组合数超出工作表限制的数量为 137,345个值

如何继续在同一工作簿的下一张纸中打印结果?

a = [100, 101, 102,...,133]
b = [250, 251, 252,...,283]
c = [300, 301, 302,...,333]
d = [430, 431, 432,...,463]

list_combined = [(p,q,r,s)   for p in a 
                             for q in b 
                             for r in c 
                             for s in d]

import xlsxwriter

workbook = xlsxwriter.Workbook('combined.xlsx')

worksheet = workbook.add_worksheet()

for row, group in enumerate(list_combined):
    for col in range(5):
        worksheet.write (row, col, group[col])
workbook.close()

2 个答案:

答案 0 :(得分:0)

首先,Python调用需要在名称之后放置括号。不允许有空格:

worksheet.write (row, col, group[col]) worksheet.write(row, col, group[col])

第二,要写入多张纸,您需要执行以下操作: 摘自this SO answer

的示例
import xlsxwriter
list_name = ["first sheet", "second sheet", "third sheet"]

workbook = xlsxwriter.Workbook(<Your full path>)
for sheet_name in list_name:
    worksheet = workbook.add_worksheet(sheet_name)
    worksheet.write('A1', sheet_name)

workbook.close()

如果您不想将任何名称传递给工作表,请删除sheet_name参数,然后将提供默认名称。

要将数据拆分为工作表,您可以轻松地将代码修改为:

for piece in iterable_data_set:
    # consider "piece" a piece of data you want to put into each sheet
    # `piece` must be an nxm matrix that contains dumpable data.
    worksheet = workbook.add_worksheet()
    for i in range(len(piece)):
        for j in range(len(piece[i])):
            worksheet.write(i, j, piece[i][j])

我建议您先寻找问题的答案,以避免出现重复的答案。如果一旦找到他们都不能解决您的问题,那么您可以去问问题,并告诉您您的问题与其他问题中的其他问题有何不同

答案 1 :(得分:0)

您可以设置上限,并在达到上限后切换到新的工作表。

下面是一个示例,该示例的限制低于Excel支持的测试限制:

import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

# Simulate a big list
biglist = range(1, 1001)

# Set max_row to your required limit. Zero indexed.
max_row = 100
row_num = 0

for data in biglist:

    # If we hit the upper limit then create and switch to a new worksheet
    # and reset the row counter.
    if row_num == max_row:
        worksheet = workbook.add_worksheet()
        row_num = 0

    worksheet.write(row_num, 0, data)
    row_num += 1

workbook.close()

输出:

enter image description here