gpt4 book ai didi

excel - Python xlsxwriter 模块 : Iterating through same set of format and conditions on multiple worksheets

转载 作者:行者123 更新时间:2023-12-04 20:16:00 26 4
gpt4 key购买 nike

使用 xlsxwriter 模块,我创建了一个 Python 脚本,它将 csv 文件内容复制到 Excel 工作表。然后创建第二个工作表,其中包含查找、计算、条件格式 - 一个模板 - 基于第一个工作表。没问题。
当我尝试循环代码时,我的问题就开始了,即将 3 个 csv 文件内容复制到 1 个工作簿中的 3 个工作表中,然后再创建 3 个应用相同模板但基于不同工作表查找的工作表。这是“将 csv 复制到 excel 工作表”代码的片段:

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

我不想复制和粘贴相同的代码,只是更改了工作表名称。

更新:考虑到 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)

最佳答案

xlsxwriter module doesn't allow me to do that. The code above would throw the following error



这不是 XlsxWriter 错误,而是一般的 python 错误。您会从以下内容中得到相同的错误:
$ cat error_test.py

def some_func():
i = 1
worksheet[i] = 123

some_func()


$ python error_test.py
Traceback (most recent call last):
File "error_test.py", line 7, in <module>
some_func()
File "error_test.py", line 5, in some_func
worksheet[i] = 123
NameError: global name 'worksheet' is not defined

您需要声明变量 worksheet某处,可能使用 worksheet.append()也是。

关于excel - Python xlsxwriter 模块 : Iterating through same set of format and conditions on multiple worksheets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25634054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com