Search code examples
pythonexport-to-excelxlsxwriter

Is it possible to apply multiple cell formats when writing to a cell with xlsxwriter?


I am new to xlsxwriter so any help is appreciated. I am trying to apply multiple cell formats to a cell within xlsxwriter and after looking around I did not see any information showing that this is possible but wanted to ask here and be sure.

Snippet of my code:

wb = xlsxwriter.Workbook('test.xlsx')
ws1 = wb.add_worksheet()
calign = wb.add_format()
calign.set_align('center')
wrap = wb.add_format()
wrap.set_text_wrap()

ws1.write(0, 0, 'Username', calign, wrap)

It gives me the error:

TypeError: write_string() takes at most 5 arguments (6 given)

I understand the error in that I am giving it 1 more argument than it can take. However is there a function in xlsxwriter that is similar to easyXF in xlwt?

Example of easyxf function utilized in writing cell that applies multiple cell formats:

format = xlwt.easyxf('alignment: horiz centre, wrap on')
ws1.write(0,0,'Text', format)

I am utilizing xlsxwriter for the conditional formatting feature so switching to xlwt is not an option unless the cell formats become more important than the conditional formatting.

Thanks.


Solution

  • After looking into source and documentation, I have to say I'm afraid it is not possible to specify multiple cell formats, or join multiple formats into a single Format class.

    You have to add a new format:

    new_format = wb.add_format()
    new_format.set_align('center')
    new_format.set_text_wrap()
    
    ws1.write(0, 0, 'Username', new_format)
    

    FYI, there is a write_rich_string() method also, which allows multiple formats - but I don't think this is what you are looking for since it would apply multiple formats to different parts/fragments of a string.