如何在xlsxwriter python中设置整行或列的格式?

时间:2015-03-10 14:30:58

标签: python python-2.7 python-3.x export-to-excel xlsxwriter

workbook = xlsxwriter.Workbook('demo1.xlsx')
worksheet = workbook.add_worksheet()
format = workbook.add_format({ 'bg_color': '#5081BB','font_color': '#FFFFFF','font_size': 12,'text_wrap':'true'})
textWrap = workbook.add_format({'text_wrap':'true'})
col = 0
row = 0
for i in data["tabledata"]:
    for j in i:
        worksheet.write(row, col, j,textWrap)
        col = col+1
    row = row+1
    col = 0
worksheet.set_row(0, 20, format)
worksheet.set_row(1, 20, format)
workbook.close()

这不正常,那么set_row和set_column的用途是什么? 如何应用特定行/列的格式?而且我需要申请 日期列的日期格式。    

worksheet.set_column(7,none,Dateformat)?

3 个答案:

答案 0 :(得分:2)

格式化在XlsxWriter中工作,就像在Excel中一样:单元格格式会覆盖行格式,而行格式又会覆盖列格式。

因此,如果您希望单元格具有与行或列相同的格式,则必须定义包含所需格式的格式对象。

答案 1 :(得分:2)

要扩展jmcnamara的答案,仅创建格式的深层副本然后进行修改是不够的。

import xlsxwriter
import copy

wb = xlsxwriter.Workbook('test.xlsx')
default = wb.add_format({'bg_color': 'yellow'})

ws = wb.add_worksheet()
ws.set_row(0, None, default)

ws.write_string(0, 0, 'default format')

fmt = copy.deepcopy(default)
fmt.set_bold()
ws.write_string(0, 1, 'bolded and yellow', fmt)

wb.close()

上面的代码产生以下内容:

Doesn't work

看来您必须使用Workbook.add_format方法来创建新格式。替换

fmt = copy.deepcopy(default)
fmt.set_bold()

fmt = wb.add_format({'bg_color': 'yellow', 'bold': True})

起作用:

Does work

答案 2 :(得分:0)

我的代码:

workbook = xlsxwriter.Workbook('demo1.xlsx')
worksheet = workbook.add_worksheet()
format = workbook.add_format({ 'bg_color': '#5081BB','font_color': 
'#FFFFFF','font_size': 12,'text_wrap':'true'})
textWrap = workbook.add_format({'text_wrap':'true'})

worksheet.set_column('B:B', 18, format)       //format formatting apply to entire B column
worksheet.set_column('C:C', None, textWrap)   //textWrap formatting apply to entire C column