谢谢大家解决这个问题。这正是我遇到的。用例:对不同类型的内容应用不同的格式,但最重要的是,对某些单元格应用其他格式(“突出显示”)。例如,添加右边框和/或下边框来分隔表格的不同部分;使用其他格式突出显示最大值。
如果返回工作簿格式的函数进行复制,恐怕填大表时会产生太多的格式实例。因此,我实施了一个解决方案,该解决方案可以预先生成具有所有亮点组合的格式。函数返回格式选择预先生成的对象之一。我不确定它是否值得分享,因为我是 Python 新手。
workbook = xlsxwriter.Workbook("test.xlsx")
### example cell formats and highlights
frm_types={
"norm": {},
"it": {"italic":True},
"bold": {"bold":True},
"boldit": {"bold":True,"italic":True}
}
frm_highlights={
"max": {"bold":True,"font_color":"#006699"},
"border_right": {"right":1},
"border_bottom": {"bottom":1},
"align_right": {"align":"right"}
}
### Creating a table of workbook formats with all highlights combinations
## Given:
# wb - workbook,
# frm - format properties as dict,
# hlist - list of highlights as dicts.
## Recursively adds levels to multidim. list - [with no highlight, with highlight],
# finally returns the last level containing a pair of workbook formats
def frm_hl_level(wb,frm,hlist):
# create two dicts. of properties: without and with first highlight from hlist
frm_nohl=copy(frm)
frm_withhl=copy(frm)
frm_withhl.update(hlist[0])
# recursion step
if len(hlist)==1:
return [
wb.add_format(frm_nohl),
wb.add_format(frm_withhl)
]
else:
return[
frm_hl_level(wb,frm_nohl,hlist[1:]),
frm_hl_level(wb,frm_withhl,hlist[1:])
]
## The formats dictionary:
# keys = format names,
# items = multidim. tables of corresponding formats with
# all highlights combinations
frm_data_dict={
fnm:
frm_hl_level( workbook, frm_types[fnm],
list(frm_highlights.values()) )
for fnm in frm_types
}
## Function which returns workbook format object
## Given
# l - list of strings: [1st = format name, rest = highlights names],
# frms, hls, tbl - format dicts., highlights dicts., dict. of formats tables;
## Returns the corresponding workbook format from the dict. of tables
def frm_select(l,frms=frm_types,hls=frm_highlights,fdt=frm_data_dict):
# list of highlights keys for identifying table indices
hl_names=list(hls.keys())
# list of indices for identifying table element
ind_l=[0 for _ in hls] # init. - format with no highlights
# add highlights to index
for nm in l[1:]:
ind_l[hl_names.index(nm)]=1
# access the element of the table
arr=fdt[l[0]]
for ind in ind_l:
arr=arr[ind]
return arr