Keep the original formatting of input.xls when opening it:
from xlrd import open_workbook input_wb = open_workbook('input.xls', formatting_info=True)
Create a new book based on this template:
from xlutils.copy import copy as copy_workbook output_wb = copy_workbook(input_wb)
Define some new cell styles:
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;")
Rate and modify your cells:
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
Save new book
output_wb.save('output.xls')
Using the example above, unmodified cells should have intact source formatting.
If you need to change the contents of a cell and would like to keep the original formatting (i.e. DO NOT use your easyxf instance), you can use this snippet:
def changeCell(worksheet, row, col, text): """ Changes a worksheet cell text while preserving formatting """
For comparisons, you can use the string methods find and rfind (which is rfind on the right). They return the index of the substring position within the string. They return -1 if the substring is not found. Ergo, you see above input_cell.value.find('deleted') >= 0 to evaluate if the substring "deleted" exists or not. For comparison .pf I used rfind , as well as something in Python called slicing .