Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix alignment problem in xlsxwriter

I am using xlsxwriter to create Excel sheets using Python. Everything works fine. I need to change for all the rows the row height to 23 and the first line of the code below did it correctly. I also need to vertically align to the center the text in all the rows and could not make it work. Any suggestion how to make it right. I am using Python 3.6.

worksheet.set_default_row(23) # Set the row height for all the rows
format = workbook.add_format()
format.set_align('vcenter')
like image 727
Menachem Avatar asked Oct 30 '25 01:10

Menachem


2 Answers

The best way to do this, and the way that Excel does it behind the scenes, is to set the row height with worksheet.set_default_row() and the formatting with worksheet.set_column().

Here is an example:

import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')

worksheet = workbook.add_worksheet()

# Set the default height of all the rows, efficiently.
worksheet.set_default_row(23)

# Format all the columns.
my_format = workbook.add_format()
my_format.set_align('vcenter')

worksheet.set_column('A:XFD', None, my_format)

workbook.close()

Note, any cell specific formatting added via the write() methods will overwrite the column format. Any data written without formats will pick up the column format.

like image 169
jmcnamara Avatar answered Oct 31 '25 14:10

jmcnamara


According to the documentation here,you can add format to the cell and apply formats when write the excel file

cell_format = workbook.add_format()
cell_format.set_align('vcenter')
worksheet.write(<some params>, cell_format)

please refer documentation for more details

https://xlsxwriter.readthedocs.io/format.html

like image 36
Rajith Thennakoon Avatar answered Oct 31 '25 14:10

Rajith Thennakoon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!