我正在编写一个函数,将值放入电子表格中,并根据值为单元格着色。现在由于某种原因,我得到一个奇怪的'NoneType'错误,这完全让我感到困惑:
Traceback (most recent call last):
File "vix.py", line 168, in <module>
printexceldaily(1990, 2015, 'All_Lows', 10, 15, 18, 28)
File "vix.py", line 166, in printexceldaily
xlbook.save('%s.xlsx' % sheetname)
File "/usr/local/lib/python3.4/dist-packages/openpyxl/workbook/workbook.py", line 281, in save
save_workbook(self, filename)
File "/usr/local/lib/python3.4/dist-packages/openpyxl/writer/excel.py", line 214, in save_workbook
writer.save(filename)
File "/usr/local/lib/python3.4/dist-packages/openpyxl/writer/excel.py", line 197, in save
self.write_data(archive)
File "/usr/local/lib/python3.4/dist-packages/openpyxl/writer/excel.py", line 98, in write_data
archive.writestr(ARC_STYLE, self.style_writer.write_table())
File "/usr/local/lib/python3.4/dist-packages/openpyxl/writer/styles.py", line 39, in write_table
self._write_cell_xfs(number_format_node, fonts_node, fills_node, borders_node)
File "/usr/local/lib/python3.4/dist-packages/openpyxl/writer/styles.py", line 159, in _write_cell_xfs
font = st.font
AttributeError: 'NoneType' object has no attribute 'font'
我试着查看styles.py和excel.py中的代码,看看我是否能找出可能导致它的原因,但我真的无法理解其中任何一个。
这是我的代码:
def printexceldaily(startyear, endyear, sheetname, start, hold, buy, end):
xlbook = Workbook()
xsheet = xlbook.active
xsheet.title = sheetname
colors = colorlist()
comparisonlist = comparisonmap(start, hold, buy, end)
length = len(comparisonlist)
# fill a list with a style for every element of colors using coloredcell
styles = [coloredcell(color) for color in colors]
def getstyle(value):
for ceiling in comparisonlist:
if value < ceiling:
z = np.where(comparisonlist==ceiling)
return styles[z[0]]
elif value > comparisonlist[length - 1]: # we need to check if value is greater than upper bound too
return styles[length - 1]
# create the cells for days
for i in range(2, 32):
xsheet.cell(row = 1, column = i).value = i
xlrow = endyear - startyear + 2
for year in range(startyear, endyear):
for month in range(12):
xsheet.cell(row = xlrow, column = 1).value = "%s, %d" % (xltomonth[month+1], year)
for day in range(monthlim[month + 1]):
curdatestr = '%d-%d-%d' % (year, month + 1, day + 1)
try:
curx = vix.loc[curdatestr, 'Low']
except KeyError:
xsheet.cell(row = xlrow, column = day+2).value = np.nan
else:
xsheet.cell(row = xlrow, column = day+2).value = curx #add value to cell
xsheet.cell(row = xlrow, column = day+2).style = getstyle(curx) #add style to cell
xlrow += 1
print('saving')
xlbook.save('%s.xlsx' % sheetname)
我已经得到了一个非常类似的“printexcelmonthly()”函数,我可以发帖,如果它会有所帮助但是出于某种原因,当我尝试保存电子表格时,这个函数会不断发布o_O
答案 0 :(得分:0)
您的代码不完整或格式错误:函数printexceldaily
的正文在哪里?您使用的是什么版本的openpyxl?
我怀疑问题与您正在创建的样式有关。这些必须是openpyxl.styles.Style
个对象的实例,这些对象始终具有font
个属性。如果要调试它,可以查看xlbook.shared_styles
。