在xlutils.copy中保留细胞颜色

时间:2013-10-02 03:48:01

标签: python excel

我正在将数据导出到格式化的Excel电子表格中,并且无法确定如何保留每个单元格的颜色。我可以用:

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

它将保留单元格大小,但由于脚本将新数据写入每个单元格,因此它会自动清除每个单元格,并在输入新数据后将其设置为白色。我想也许我发现这个“黑客”可以实现解决这个问题,但我不知道如何将它应用到我自己的脚本中。

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

这是我目前的脚本:

#!/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)

关于如何实现这一目标的任何想法都将非常感激。谢谢!

0 个答案:

没有答案