【发布时间】:2018-12-04 00:36:58
【问题描述】:
我正在使用 xlrd 和 xlwt 来检查某些单元格并检查它们是否符合某些标准。如果它们符合我继续前进的标准,如果不符合,我想将文本着色为红色。单元格之间的格式会发生变化,有些有背景颜色,有些是粗体,有些是不同的大小,所有这些差异都需要保留。
有什么简单的方法吗?
我可以使用 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 中,但仔细查看这个值后,我发现它是一个整数,让我完全不知道如何从中提取样式的某些属性,所以我只能更改字体颜色。
正如我之前所说,有没有简单的方法可以做到这一点?
【问题讨论】: