Python xlwt: save all styles but one

I use xlrd and xlwt to go through certain cells and check them against certain criteria. If they meet the criteria that I pass, if not, I want to color the RED text. Formatting from cell to cell changes, some of them have a background color, some are bold, and some are different, and all these differences must be preserved.

Is there an easy way to do this?

I can duplicate the current format of one of the cells, which I know quite easily using 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' ) 

but this, of course, runs into problems, because not every cell has the same formatting (as I explained above, some of them have background colors or no borders or different font styles). I was looking for style preservation using this code from another StackOverflow question:

 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') 

It seems that the style is held in Cell.xf_idx, but after a closer examination of this value, I found that it is an integer, leaving me completely confused about how to extract certain style attributes from it that I can only change the font color.

As I said, is there an easy way to do this?

+6
source share
1 answer

You should check the xlutils.styles module, open excel with formatting_info = True and follow your logic and change the relative cell style and then save excel again.

 open_workbook(excel_file_full_path, formatting_info=True) 
+1
source

Source: https://habr.com/ru/post/949903/


All Articles