Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
like image 814
Greg Avatar asked Oct 20 '11 01:10

Greg


People also ask

Can XLRD write to Excel?

With the xlrd and xlwt Python Addon libraries you can easily read and write directly to Excel files (.


1 Answers

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

like image 126
Cito Avatar answered Oct 26 '22 14:10

Cito