xlwt.Style.EasyXFCallerError: section 'fill' is unknown

xlwt.Style.EasyXFCallerError: section 'fill' is unknown

我有一个数据框,我在其中进行更新,例如写入特定单元格并将背景色添加到特定单元格。在 dataframe 中看起来不错。但是当我将dataframe转换为excel时,发现下面的错误。

df.to_excel("test_sheet.xls") 导致错误。

Traceback (most recent call last):
  File "scoring_model.py", line 441, in <module>
    pf = ScoringModel()
  File "scoring_model.py", line 12, in __init__
    self.start_scoring()
  File "scoring_model.py", line 185, in start_scoring
    df.to_excel("test_sheet.xls")
  File "D:\Projects\Scoring Model\venv\lib\site-packages\pandas\io\formats\style.py", line 187, in to_excel
    engine=engine)
  File "D:\Projects\Scoring Model\venv\lib\site-packages\pandas\io\formats\excel.py", line 662, in write
    freeze_panes=freeze_panes)
  File "D:\Projects\Scoring Model\venv\lib\site-packages\pandas\io\excel.py", line 1708, in write_cells
    style = self._convert_to_style(cell.style, fmt)
  File "D:\Projects\Scoring Model\venv\lib\site-packages\pandas\io\excel.py", line 1771, in _convert_to_style
    style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
  File "D:\Projects\Scoring Model\venv\lib\site-packages\xlwt\Style.py", line 733, in easyxf
    field_sep=field_sep, line_sep=line_sep, intro_sep=intro_sep, esc_char=esc_char, debug=debug)
  File "D:\Projects\Scoring Model\venv\lib\site-packages\xlwt\Style.py", line 638, in _parse_strg_to_obj
    raise EasyXFCallerError('section %r is unknown' % section)
xlwt.Style.EasyXFCallerError: section 'fill' is unknown

使用最新的 python3.5xlwt 1.3。 有没有人发现同样的错误?

谢谢

你能粘贴到 xlwt_stylestr 吗?

那里可能有错字 [缺少 space 字符?],因为我检查了异常的来源 - https://github.com/python-excel/xlwt/blob/master/xlwt/Style.py#L639

根据评论,你可以试试:

xlwt_stylestr = 'pattern: pattern solid, fore_colour red;'

然后将其传递给 write 可调用对象: https://xlwt.readthedocs.io/en/latest/api.html#xlwt.Worksheet.Worksheet.write styled.to_excel('styled.xlsx')

你能试试这个吗:

def bg_red(val):
    # this will receive each value in the excel
    # so if you want to add conditional logic, you can
    # add here
    return 'background-color: red'

style_obj  = df.style.applymap(bg_red)
style_obj.to_excel('styled_doc.xlsx')

更多信息请参考: https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html

虽然听起来很蹩脚,但我遇到了同样的困难,当我改变时停止了

df.to_excel("test_sheet.xls")

df.to_excel("test_sheet.xlsx")

FWIW 我也在使用 'xlsxwriter'