使用python从Excel有条件地格式化文本string

我想格式化一个电子表格(xls或xlsx),以便任何包含单词或以某个string结尾的单元格都通过用特定颜色填充背景进行格式化。

例如,如果单元格包含单词“已删除”,请将其填充黑色并将文本涂成白色。 如果单元格以“.pf”结尾,则将单元格涂成红色。

我在几年前发现了一个类似的问题,提出如下build议:

import xlrd import xlutils.copy inBook = xlrd.open_workbook('input.xls', formatting_info=True) outBook = xlutils.copy.copy(inBook) 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') 

虽然这会将input.xls中的值复制到output.xls,但这似乎并没有传递格式(input.xls中的testing值在打开output.xls时不再被格式化,条件格式规则也不会在“pipe理规则“在Excel中。

数字值的“if”语句似乎工作,但是,我正在寻找一种方法来格式化包含某些string的单元格。 谢谢!

打开时保留原始的input.xls格式:

 from xlrd import open_workbook input_wb = open_workbook('input.xls', formatting_info=True) 

基于此模板创build一个新的工作簿:

 from xlutils.copy import copy as copy_workbook output_wb = copy_workbook(input_wb) 

定义一些新的单元格样式:

 from xlwt import easyxf red_background = easyxf("pattern: pattern solid, fore_color red;") black_with_white_font = easyxf('pattern: pattern solid, fore_color black; font: color-index white, bold on;") 

评估和修改您的单元格:

 input_ws = input_wb.sheet_by_name('StackOverflow') output_ws = output_wb.get_sheet(0) for rindex in range(0, input_ws.nrows): for cindex in range(0, input_ws.ncols): input_cell = input_ws.cell(rindex, cindex) if input_cell.value[ input_cell.value.rfind('.'): ] == 'pf': output_ws.write(rindex, cindex, input_cell.value, red_background) elif input_cell.value.find('deleted') >= 0: output_ws.write(rindex, cindex, input_cell.value, black_with_white_font) else: pass # we don't need to modify it 

保存您的新工作簿

 output_wb.save('output.xls') 

使用上面的例子,未修改的单元格应该具有原始格式。

如果您需要更改单元格内容,并希望保留原始格式(即不使用自定义的easyxf实例),则可以使用以下代码片段:

 def changeCell(worksheet, row, col, text): """ Changes a worksheet cell text while preserving formatting """ # Adapted from https://stackoverflow.com/a/7686555/1545769 previousCell = worksheet._Worksheet__rows.get(row)._Row__cells.get(col) worksheet.write(row, col, text) newCell = worksheet._Worksheet__rows.get(row)._Row__cells.get(col) newCell.xf_idx = previousCell.xf_idx # ... changeCell(worksheet_instance, 155, 2, "New Value") 

为了比较,你可以使用string方法findrfind (从右边search)。 它们返回string中子string位置的索引。 如果未find子string,则返回-1 。 Ergo,您可以在input_cell.value.find('deleted') >= 0上面看到,以评估子string“deleted”是否存在。 对于.pf比较,我使用rfind以及Python中称为切片的东西。