1

I am exporting data to a formatted excel spreadsheet and am having trouble figuring out how to preserve the colors for each cell. I can use:

workbook_file = open_workbook(file_name, on_demand=True, formatting_info=True)

and it will preserve the cell size, but since the script writes new data into each cell, it automatically clears each cell and makes it white once it inputs the new data. I am thinking that perhaps this "hack" I found could be implemented to solve exactly this problem, but I am not sure how to apply this to my own script.

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

Here is the script I currently have:

#!/usr/bin/env python

import xlrd
from xlutils.copy import copy
from xlrd import open_workbook

from canada import city, CanadaWeather
from canadausa import uscity, USWeather
from selectcities import selectcity, SelectCanadaWeather

cw = CanadaWeather()
cw.retrieveAll()

#Select Canada Cities that are not updated by 5:45am CT.

sc = SelectCanadaWeather()
sc.retrieveAllSelect()

#US Weather

uw = USWeather()
uw.retrieveAll()

cities = cw.getCities()
uscities = uw.getUSCities()
selectcities = sc.getSelectCities()

## 
# writing to excel
##
file_name = 'TEST_fcst_hilo_TEST.xls'
new_file_name = 'fcst_hilo.xls'
row = 1


column_names = ["high0", "low1", "high1", "low2", "high2",
                "low3", "high3", "low4", "high4", "low5",
                "high5", "low6", "high6"]

uscolumn_names = ["high0", "low1", "high1", "low2", "high2",
                  "low3", "high3", "low4", "high4"]

select_column_names = ["high0", "low1", "high1", "low2", "high2",
                       "low3", "high3", "low4", "high4", "low5",
                       "high5"]

workbook_file = None
try :
        # currently xlwt does not implement this option for xslx files
        workbook_file = open_workbook(file_name, on_demand=True, formatting_info=True)
except :
        workbook_file = open_workbook(file_name, on_demand=True)

workbook = copy(workbook_file)
sheet = workbook.get_sheet(0)

for city in cities:
    for column, col_name in enumerate(column_names, start=2):
        sheet.write(city.excel_row, column, getattr(city, col_name))

for uscity in uscities:
    for column, col_name in enumerate(uscolumn_names, start=2):
                sheet.write(uscity.usexcel_row, column, getattr(uscity, col_name))

for selectcity in selectcities:
        for column, col_name in enumerate(select_column_names, start=2):
                sheet.write(selectcity.excel_row, column, getattr(selectcity, col_name))

workbook.save(new_file_name)

Any ideas on how I could accomplish this would be much appreciated. Thank you!

Community
  • 1
  • 1
hunter21188
  • 405
  • 2
  • 7
  • 29

0 Answers0