Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set formatting for entire row or column in xlsxwriter Python?

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()

this doesn't properly work, then what is the use of set_row and set_column?
How to apply the format for specific row/column? I also need to apply date format for date columns.

worksheet.set_column(7, none, Dateformat)
like image 813
Mj. Avatar asked Mar 10 '15 14:03

Mj.


People also ask

How do I autofit in XlsxWriter?

The with of 1 unit of the xlsxwriter columns is about equal to the width of one character. So, you can simulate autofit by setting each column to the max number of characters in that column.


2 Answers

Formatting works in XlsxWriter like in Excel: a cell format overrides a row format which in turn overrides a column format.

So if you want a cell to have a format plus the same formatting as the row or column you will have to define a format object that contains all the formats that you want.

like image 69
jmcnamara Avatar answered Sep 21 '22 08:09

jmcnamara


To expand on jmcnamara's answer, it's not enough to create a deep copy of the format and then modify it.

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()

The code above produces the following:

Doesn't work

It appears that you must use the Workbook.add_format method method to create a new format. Replacing

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

with

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

does work:

Does work

like image 26
Zack Sheffield Avatar answered Sep 24 '22 08:09

Zack Sheffield