我正在将数据导出到格式化的 excel 电子表格,并且无法弄清楚如何保留每个单元格的颜色。我可以用:
workbook_file = open_workbook(file_name, on_demand=True, formatting_info=True)
并且它将保留单元格大小,但是由于脚本将新数据写入每个单元格,因此它会自动清除每个单元格并在输入新数据后将其变为白色。我在想也许我发现的这个“hack”可以用来解决这个问题,但我不确定如何将它应用到我自己的脚本中。
使用 python 的 xlrd、xlwt 和 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)
关于如何实现这一点的任何想法将不胜感激。谢谢!