Adjust cell width in Excel

心已入冬 提交于 2019-11-27 20:40:55

You could use set_column as follows:

worksheet1.set_column(1, 1, 25)

This is defined as follows:

set_column(first_col, last_col, width, cell_format, options)

If you want to autofit all of the columns automatically, then you will need to use the win32com interface as follows:

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'file.xlsx')
ws = wb.Worksheets("Sheet1")
ws.Columns.AutoFit()
wb.Save()
excel.Application.Quit()

This can easily be done after you closed the file using your current xlsxwriter code. Note, you might need to supply a full path to your file.

Unfortunately xlsxwriter doesnt provide autofit option.

You can however track the largest entry for each column and then set the column width in the end with set column command.

set_column(first_col, last_col, width, cell_format, options)

In your case for instance, you should set the width of B column to the length of the largest string.

width= len("long text hidden test-1")
worksheet1.set_column(1, 1, width)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!