python - 尝试使用 python 在 xlwt 中设置单元格颜色时丢失属性错误

标签 python excel runtime-error xlwt

我正在尝试使用 python 的 xlwt 包将 Excel 电子表格的颜色更改为颜色代码数据。这是我当前的代码:

from xlrd import open_workbook
from tempfile import Temporary File
from xlwt
import sys
import csv

....
....#Some other code

style = xlwt.XFStyle() #this is the line throwing the error
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = xlwt.Style.colour_map['red']

pattern.pattern_fore_colour = xlwt.Style.colour_map['red']
newSheet.write(row, col, values[row - 1][col], pattern)

....
....#Some other code

存在其他代码部分,因为它的脚本比显示的更长,但这些代码部分与此问题无关

运行时我得到以下堆栈跟踪:

Traceback (most recent call last):
   File "excel-procesor.py", line 85, in <module>
        newSheet.write(row, col, values[row - 1][col], pattern)
   File "/usr/local/lib/python2.7/dist-packages/xlwt/Worksheet.py", line 1030, in write self.row(r).write(c, label, style)
   File "/usr/local/lib/python2.7/dist-packages/xlwt/Row.py", line 234, in write self.__adjust_height(style)
   File "/usr/local/lib/python2.7/dist-packages/xlwt/Row.py", line 64, in __adjust_height
        twip = style.font.height
AttributeError: 'Pattern' object has no attribute 'font'

我正在使用How to change background color of excel cell with python xlwt library?python xlwt set custom background colour of a cell作为指导。

最佳答案

根据源码:

xlwt.Worksheet.write(self, r, c, label='', style=<xlwt.Style.XFStyle object at 0x053AEA10>)

write 应该接收 style 作为参数,而不是直接接收 Pattern 对象。

您应该尝试将模式对象放入 style 并传递 style 作为参数:

style.pattern = pattern
newSheet.write(row, col, values[row - 1][col], style)

一些examples我发现如何使用 xlwt 非常有用,包括如何设置样式

关于python - 尝试使用 python 在 xlwt 中设置单元格颜色时丢失属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16861892/

相关文章:

python - 使用嵌套 for 循环在每个坐标处评估函数 - python

c# - 读取Excel文件!总是出现一个对话框要求保存

excel - MS Excel 自动更改单元格变量

android - Gradle 有错误,但构建良好

excel - 从计时器子调用时,ThisWorkbook.RefreshAll 不起作用

python - 我该如何处理基本矩阵?

python - 使用 Python 将字典打印到 CSV 文件

python - 获取另一个应用程序的所有快捷方式的列表

vba - 通过 COM 创建 TimeSpan 实例

ubuntu - WslRegisterDistribution 失败,出现错误 : 0x80070241 Windows cannot verify the digital signature for this file