我想在一个工作簿中添加一些工作表。
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()
但它的作用是它只创建一个对应于“C.csv”而不是“A.csv”和“B.csv”的表格。 从我得到的,它是因为每次循环它创建一个新的工作簿。我想在同一个工作簿上创建3张。
另外,有一个条件,我想仅在循环内初始化工作簿构造函数。
答案 0 :(得分:3)
下面是一个示例代码,但它在for循环之外有工作簿构造函数,它可以满足您的需求!
输入csv文件:
示例代码
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()
<强>输出强>
答案 1 :(得分:2)
使用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