我正在使用 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中,但仔细看这个值后,我发现它是一个整数,让我完全不知道如何从中提取样式的某些属性所以我只能更改字体颜色。
正如我之前所说,有什么简单的方法可以做到这一点吗?
最佳答案
您应该查看模块 xlutils.styles ,打开带有 formatting_info=True 的 excel,然后执行您的逻辑并更改相关单元格样式,然后再次保存 excel。
open_workbook(excel_file_full_path, formatting_info=True)
关于 python xlwt : preserve all styles but one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17765021/