我正在使用xlrd和xlwt来浏览某些单元格并检查它们是否符合某些条件.如果他们符合我继续前进的标准,如果没有,我想为文本RED着色.从单元格到单元格的格式更改,一些具有背景颜色,一些是粗体,一些是不同的大小,所有这些差异需要保留.
有没有简单的方法来做到这一点?
我可以使用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'
)
Run Code Online (Sandbox Code Playgroud)
但这当然会遇到问题,因为不是每个单元都有相同的格式(如上所述,有些具有背景颜色或没有边框或不同的字体样式).我考虑使用另一个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')
Run Code Online (Sandbox Code Playgroud)
看起来好像风格是在Cell.xf_idx中保存的,但是仔细看看这个值后,我发现它是一个整数,让我完全不知道如何从中提取样式的某些属性,这样我才能仅改变字体颜色.
正如我之前所说,有没有简单的方法来实现这一目标?
您应该检查模块xlutils.styles,使用formatting_info = True打开Excel,然后执行逻辑并更改相对单元格样式,然后再次保存Excel。
open_workbook(excel_file_full_path, formatting_info=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1523 次 |
| 最近记录: |