我正在使用xlrd和xlwt来遍历特定单元格并检查它们是否满足特定条件。如果它们符合条件,我就继续进行下一个操作,如果不符合,我想将文本颜色设置为红色。从单元格到单元格的格式都不同,有些有背景颜色,有些是加粗的,有些是不同大小的,所有这些差异都需要保留。
有没有简单的方法来实现呢?
我可以使用easy_xf很容易地复制我知道的某个单元格的当前格式,
有没有简单的方法来实现呢?
我可以使用easy_xf很容易地复制我知道的某个单元格的当前格式,
form = xlwt.easyxf(
'font: name Gotham Narrow Book, height 140, color red;'
'borders: left thin, right thin, top thin, bottom thin;'
'pattern: pattern solid, pattern_fore_colour white, pattern_back_colour white'
)
但这当然会遇到问题,因为不是每个单元格都有相同的格式(正如我上面解释的那样,有些具有背景颜色或没有边框或不同的字体样式)。我查看了来自另一个 StackOverflow 问题的代码,以保留样式:
def _getOutCell(outSheet, colIndex, rowIndex):
""" HACK: Extract the internal xlwt cell representation. """
row = outSheet._Worksheet__rows.get(rowIndex)
if not row: return None
cell = row._Row__cells.get(colIndex)
return cell
def setOutCell(outSheet, col, row, value):
""" Change cell value without changing formatting. """
# HACK to retain cell style.
previousCell = _getOutCell(outSheet, col, row)
# END HACK, PART I
outSheet.write(row, col, value)
# HACK, PART II
if previousCell:
newCell = _getOutCell(outSheet, col, row)
if newCell:
newCell.xf_idx = previousCell.xf_idx
# END HACK
outSheet = outBook.get_sheet(0)
setOutCell(outSheet, 5, 5, 'Test')
outBook.save('output.xls')
看起来样式是保存在Cell.xf_idx中的,但是仔细查看这个值后,我发现它是一个整数,让我完全不知道如何从中提取某些样式属性,以便我可以仅更改字体颜色。
正如我之前所说,有没有一种简单的方法可以实现这个目标?