首页 > 解决方案 > 如何在不更改其他格式/样式的情况下更改 Excel 单元格的颜色?

问题描述

我正在开发一个功能来编辑旧的“xls”文件,而不是“xlsx”。我正在使用 xlrd、xlutils 和 xlwt 等软件包。我想更改单元格的颜色而不更改其他样式,例如粗体和中心。颜色是基于用户输入的用户定义的 RGB 颜色。

我写了一些这样的代码,但我找不到将样式信息从“xlrd.formatting.XF”传输到“xlwt.Style.XFStyle”的方法。所以,我的代码会丢失样式信息。

reader_book = xlrd.open_workbook(self.filePath, formatting_info=True)
reader_sheet = reader_book.sheet_by_name(self.sheetName)
writer_book = copy(reader_book)
writer_sheet_index = [s.name for s in reader_book.sheets()].index(self.sheetName)
writer_sheet = writer_book.get_sheet(writer_sheet_index)
reader_cell = reader_sheet.cell(rowx=int(row_str)-1, colx=int(col_str)-1)
print("reader_cell.xf_index is", reader_cell.xf_index)
fmt = reader_book.xf_list[reader_cell.xf_index]
print("type(fmt) is", type(fmt))
print("fmt.dump():",  fmt.dump())
xlwt.add_palette_colour("custom_colour", 0x21)
writer_book.set_colour_RGB(0x21, 244, 0, 0)
style = xlwt.easyxf('pattern: pattern solid, fore_colour custom_colour')
print('style', type(style))
writer_sheet.write(int(row_str)-1, int(col_str)-1, reader_cell.value, style)
writer_book.save(self.filePath)

有什么方法可以做到这一点吗?或者,有没有其他软件包可以做到这一点?

非常感谢。

标签: pythonxlrdxlwtxlutils

解决方案


推荐阅读