2

I am using the xlrd, xlwt & xlutils library in python to read & write from an excel sheet. So, I have successfully read & written to the excel sheet.

But I need some directions in capturing the format of the cell I am reading from & applying the same format to the cell I am writing to.

Below is what I have tried -

#Open excel sheet & read from tab1
rb = open_workbook(r'C:\Users\abc\excel.xls', formatting_info=True)
sheet = rb.sheet_by_name("tab1")

#Search the excel sheet for the string and return location of Cell
def searchStringCell(searchString):
    for i in range(sheet.nrows):
         row = sheet.row_values(i)
         for j in range(len(row)):
              if row[j] == searchString:
                    return i,j

# Search string to be read
header='<Title>'
headerTitleX,headerTitleY=searchStringCell(header)
cell = sheet.cell(headerTitleX, headerTitleY)
print "Title Cell : (",headerTitleX,",",headerTitleY,")"

#Write data to cell which is 2 columns to the right of the cell already read
wb = copy(rb)
w_sheet = wb.get_sheet(0)
w_sheet.write(headerTitleX, headerTitleY+2, 'New data')

#Have tried the below; not sure about what to do
fmt = rb.xf_list[cell.xf_index]
bg=fmt.background.pattern_colour_index
rgb = wb.colour_map[bg]

#Save the changes
wb.save(r'C:\Users\abc\excel.xls')

I have tried to read fmt, bg & rgb from the sheet; but I am unsure of how to apply the same format of the cell from which data is read & apply it to the new cell. Thanks.

0nir
  • 1,345
  • 4
  • 20
  • 41

0 Answers0