使用xlsxwriter模塊,我創建了一個Python腳本,可以將csv文件內容複製到excel工作表中。然後用查找,計算和條件格式創建第二張工作表 - 一個基於第一張工作表的模板。沒問題。
當我嘗試循環代碼時,即將3個csv文件內容複製到1個工作簿中的3個工作表中,然後再創建另外3個應用相同模板但基於不同工作表查找的工作表時,我的問題就開始了。這裏的「複製到CSV Excel工作表」代碼片段:Python xlsxwriter模塊:在多個工作表上迭代相同的一組格式和條件
workbook = Workbook(csvFile[:-4] + '.xlsx', {'strings_to_numbers': True})
align = workbook.add_format({'align':'center','text_wrap':True})
for csvfile in (glob.glob(filepath + '\\*.csv')):
worksheet = workbook.add_worksheet(header[2])
with open(csvfile, 'rb') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet.set_column('A:A',65)
worksheet.set_column('B:P',12)
worksheet.write(r, c, col, align)
我想要做這樣的事情:
workbook = Workbook(csvFile[:-4] + '.xlsx', {'strings_to_numbers': True})
align = workbook.add_format({'align':'center','text_wrap':True})
for i, csvfile in (glob.glob(filepath + '\\*.csv')):
worksheet[i] = workbook.add_worksheet(header[i])
with open(csvfile, 'rb') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet[i].set_column('A:A',65)
worksheet[i].set_column('B:P',12)
worksheet[i].write(r, c, col, align)
xlsxwriter模塊不允許我這樣做。上面的代碼會拋出以下錯誤:
File "C:\workspace\automagic.py", line 103, in create_xls
worksheet[i] = workbook.add_worksheet(header[i])
NameError: global name 'worksheet' is not defined
我不想複製和粘貼相同的代碼只改變工作表名稱。
UPDATE:考慮採取jmcnamara的評論,我能修改我的代碼如下所示:
worksheet = ['worksheet0','worksheet1','worksheet2']
workbook = Workbook(csvFile[:-4] + '.xlsx', {'strings_to_numbers': True})
align = workbook.add_format({'align':'center','text_wrap':True})
for i, csvfile in enumerate(glob.glob(filepath + '\\*.csv')):
testtype = csvfile.split('.')[3].split('_')[1]
worksheet[i] = workbook.add_worksheet(testtype)
with open(csvfile, 'rb') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet[i].set_column('A:A',65)
worksheet[i].set_column('B:P',12)
worksheet[i].write(r, c, col, align)
來自模塊開發人員的幫助有所幫助。 :) – user2771721 2014-09-03 21:53:33