我正在使用几个逗号分隔的CSV文件并使用它们生成XLS电子表格,其中文件的名称在电子表格中成为单独的标签。我生成的代码产生了我想要的结果,除了打开电子表格时我收到以下警告:"由于超出了最大字体数,因此该文件中的某些文本格式可能已更改。关闭其他文档并重试可能会有所帮助。"我很确定问题是由于代码试图将单元格格式更改为超出65536行限制而产生的,但我不确定如何限制行更改。我需要四列不超过几百行。
import csv, glob, xlwt, sys, os
csvFiles = os.path.join(LogFileFolder, "*")
wb = xlwt.Workbook()
colNames = ['iNFADS_FAC','CAT','Crosswalk_FAC','FAC']
for filename in glob.glob(csvFiles):
(f_path, f_name) = os.path.split(filename)
(f_short_name, f_extension) = os.path.splitext(f_name)
ws = wb.add_sheet(f_short_name)
with open(filename, 'rb') as csvf:
csvReader = csv.reader(csvf)
for rowx, row in enumerate(csvReader):
for colx, value in enumerate(row):
if value in colNames:
ws.write(rowx, colx, value, xlwt.easyxf(
"border: top medium, right medium, bottom double, left medium;
font: bold on; pattern: pattern solid, fore_color pale_blue;
align: vert centre, horiz centre"))
elif value not in colNames:
ws.write(rowx, colx, float(value),
xlwt.easyxf("align: vert centre, horiz centre"))
##This second "xlwt.easyxf(align...)" part is the offending section of the code, if
##I remove just that part then the problem goes away. Is there a way to keep
##it within the 65536 limit here?
else:
pass
wb.set_active_sheet = 1
outXLS = os.path.join(LogFileFolder, "FAC-CAT Code Changes.xls")
wb.save(outXLS)
答案 0 :(得分:2)
我要感谢谷歌集团的John Machin' python-excel'回答我的问题。显然,解决方案是将easyxf部分移动到脚本中较早的变量,然后在需要时调用它。所以脚本应该是:
csvFiles = os.path.join(LogFileFolder, "*")
wb = xlwt.Workbook()
headerStyle = xlwt.easyxf("border: top medium, right medium, bottom double," \
"left medium; font: bold on; pattern: pattern solid, fore_color pale_blue;" \
"align: vert centre, horiz centre")
valueStyle = xlwt.easyxf("align: vert centre, horiz centre")
colNames = ['iNFADS_FAC','CAT','Crosswalk_FAC','FAC']
for filename in glob.glob(csvFiles):
(f_path, f_name) = os.path.split(filename)
(f_short_name, f_extension) = os.path.splitext(f_name)
ws = wb.add_sheet(f_short_name)
with open(filename, 'rb') as csvf:
csvReader = csv.reader(csvf)
for rowx, row in enumerate(csvReader):
for colx, value in enumerate(row):
if value in colNames:
ws.col(colx).width = 256 * 15
ws.write(rowx, colx, value, headerStyle)
elif value not in colNames:
ws.write(rowx, colx, float(value), valueStyle)
else:
pass
wb.set_active_sheet = 1
outXLS = os.path.join(LogFileFolder, "FAC-CAT Code Changes.xls")
wb.save(outXLS)