Python Excel (xlrd, xlwt) - How to copy a style from one cell and put it on another

Greg picture Greg · Oct 20, 2011 · Viewed 8.7k times · Source

Specifically I'm trying to open an existing workbook, and write some data to it.

However whenever I write the data it obliterates the borders on those cells.

So I'm wondering if there's a way to copy the style of that cell before writing to it and then reapply it.

I think I might be on the right track with this code?

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

But I'm getting this error:

AttributeError: NamedStyle instance has no attribute 'font'

Answer

Cito picture Cito · Nov 10, 2011

The problem here is that a xlrd.NamedStyle is very different from xlwt.XFStyle.

The question seems to be a duplicate of Preserving styles using python's xlrd,xlwt, and xlutils.copy