Python:在多个excel工作表中组合输出

2024-10-01 19:29:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手。我已经生成了由24个数字组成的3个数字组合(总组合2024)。我的目的是将这些组合放在同一工作簿的不同excel表格中。例如,每张图纸中有100个组合。我从这个网站上得到了一些参考资料,并尝试使用它。但是,所有的组合仍然在同一张表中生成

import xlsxwriter


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


import itertools as it
combin = it.combinations(range(1,25),3)
count_combin = []
for i in combin:
    count_combin.append(i)



max_row = 100
row_num = 0

for data in count_combin:

    if row_num == max_row:
        worksheet = workbook.add_worksheet()
        row_num = 0

for row, group in enumerate(count_combin):
    for col in range(3):
        worksheet.write (row, col, group[col])
        row_num += 1

workbook.close()

请告诉我编码有什么问题?


Tags: inimportaddforcountrangeit数字
1条回答
网友
1楼 · 发布于 2024-10-01 19:29:41

这应该可以做到(在代码注释中解释)

import xlsxwriter
import itertools as it
from math import floor

workbook = xlsxwriter.Workbook('test.xlsx')
combin = it.combinations(range(1,25),3)

max_row = 100
lst_combin = list(combin)

for x, c in enumerate(lst_combin):
    # if x is zero or reachs max_row add a new work sheet
    if x % max_row == 0:
        worksheet = workbook.add_worksheet()

    # nx = x unless x is greater than max row ..
    # .. then nx = x  - max rows multiplied by the number of max rows in x
    nx = x
    if x > max_row:
        nx = x - max_row*(floor(x/max_row))

    worksheet.write(nx, 0, c[0])
    worksheet.write(nx, 1, c[1])
    worksheet.write(nx, 2, c[2])

    workbook.close()

相关问题 更多 >

    热门问题