如何在 xlsxwriter 中添加新作品 sheet 到工作簿

How to add a new work sheet to work book in xlsxwriter

我想在一个工作簿中添加一些 sheet。

sheets = ["A.csv", "B.csv", "C.csv"]
for sh in sheets:
    workbook = xlsxwriter.Workbook('myxlsx.xlsx')
    worksheet = workbook.add_worksheet(sh)
    worksheet.write(1,1,"abcd")
    workbook.close()

但它所做的只是创建一个 sheet 对应于 "C.csv" 而不是 "A.csv" 和 "B.csv" 据我所知,这是因为每次循环都会创建一个新的工作簿。我想在同一个工作簿上创建 3 个 sheet。

另外,有一个条件,我只想在循环内初始化工作簿构造函数。

这是一个示例代码。 工作簿构造函数需要在 for 循环之外创建,它可以满足您的需求!

Input csv files:

SAMPLE CODE

import os
import glob
import xlsxwriter
import csv

flist = [os.path.basename(x) for x in glob.glob(os.getcwd() + '\*.csv')]

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

for sh in flist:
    worksheet = workbook.add_worksheet(sh)
    with open(sh, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)

workbook.close()

OUTPUT

使用 forloop 外部的 .close() 修复您的代码,使其看起来像这样

sheets = ["A.csv", "B.csv", "C.csv"]
for sh in sheets:
   workbook = xlsxwriter.Workbook('myxlsx.xlsx')
   worksheet = workbook.add_worksheet(sh)
   worksheet.write(1,1,"abcd")
workbook.close() # should be outside the for loop