python - 如何在不更改其他格式/样式的情况下更改 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)
有什么方法可以做到这一点吗?或者,有没有其他软件包可以做到这一点?
非常感谢。
解决方案
推荐阅读
- go - 写入具有多个 goroutine 的互斥映射是否比一个更快?为什么?
- javascript - 日期和时间选择器,禁用未来和过去的日期和时间
- php - 如何使用foreach()将数组中的所有行组合为一个输入?
- filemaker - 选项卡上的新记录按钮有问题?
- android - 无法获取 PageUp/PageDown KeyEvent
- python - 如何使用每个组的不同条件进行 drop_duplicate?
- javascript - 具有每月持续时间选项(1 个月、2 个月、3 个月等)的 Bootstrap 日期时间选择器
- javascript - 是否有更简单的方法可以推送到 JSON 数组或创建该数组(如果它尚不存在)?
- c# - 如何从 2 个动态文本框中计算值并在第三个动态文本框中显示?
- sql - 为什么 CASE 语句应该在 select 语句中?