我有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()
您可以设置上限并在达到限制后切换到新工作表。
下面是一个示例,其下限超出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()
输出:
首先,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])
我建议您首先查找问题的答案,以避免重复的答案。如果一旦找到它们没有解决你的问题,那么你可以去问它,也告诉你的问题与其他问题中的其他问题有什么不同。