Python Excel (xlrd, xlwt) - 如何复制一个单元格的样式到另一个单元格

7 投票
1 回答
9537 浏览
提问于 2025-04-17 04:40

我想打开一个已经存在的工作簿,然后往里面写一些数据。

可是每次我写数据的时候,那个单元格的边框就会消失。

所以我在想,有没有办法在写数据之前先复制一下那个单元格的样式,然后再把样式应用回去。

我觉得我可能在这个代码上走对了方向?

from xlrd import open_workbook
from xlwt import easyxf
from xlutils.copy import copy
from xlutils.styles import Styles

rb=open_workbook('source.xls',formatting_info=True)
styles = Styles(rb)
rs=rb.sheet_by_index(0)
wb=copy(rb)
ws=wb.get_sheet(0)

for i,cell in enumerate(rs.col(2)):
    if not i:
      continue
    cell_style = styles[rs.cell(i,2)]
    ws.write(i,2,cell.value,cell_style)

wb.save('output.xls')

但是我遇到了这个错误:

AttributeError: NamedStyle instance has no attribute 'font'

1 个回答

3

这里的问题是,xlrd.NamedStyle 和 xlwt.XFStyle 是非常不同的东西。

这个问题看起来和 使用 Python 的 xlrd、xlwt 和 xlutils.copy 保留样式 这个问题是重复的。

撰写回答