1

I'm trying to add rows to an Excel file via Python (need this to run and refresh daily). The Excel file is essentially a template, at the top of which has some cells for some of the words within a cell have specific formatting, i.e. cell value "That cat is fluffy".

I can't quite find a way to get Python+Excel to work together to preserve that formatting - it takes the format of the first letter in the cell and applies it across the board.

From what I can tell, this is an issue with preserving rich text, but I haven't been able to find a package that can preserve rich text, read and write excel files.

I followed this thread to come up with the code below: writing to existing workbook using xlwt

But, it looks like that copy step from the xlutils package isn't preserving the rich text formatting.

import xlwt
import xlrd
from xlutils.copy import copy

rb = xlrd.open_workbook(templateFile,formatting_info=True)

r_sheet = rb.sheet_by_index(0)
wb = copy(rb) 

w_sheet = wb.get_sheet(0) 
xlsfile = Infile
insheet = xlrd.open_workbook(xlsfile,formatting_info=True).sheets()[0]
outrow_idx = 10
for row_idx in xrange(insheet.nrows):
    for col_idx in xrange(insheet.ncols):
        w_sheet.write(outrow_idx, col_idx, 
                       insheet.cell_value(row_idx, col_idx))
    outrow_idx += 1

wb.save(Outfile)
Community
  • 1
  • 1
econgineer
  • 1,117
  • 10
  • 20

1 Answers1

0

Please refer to this link over here, as it may help you with keeping the formatting

Preserving styles using python's xlrd,xlwt, and xlutils.copy

though it doesn't keep the cell comments

Community
  • 1
  • 1