Adding @Mehdi Zare's comment as an answer as i nearly implemented by hand.
xlsxwriter
now contains autofit
method for sheets.
sheet.autofit()
may be enough for you. There are some limitations btw. Method docs: https://xlsxwriter.readthedocs.io/worksheet.html#worksheet-autofit
For the limitations, read the docs' description:
There is no option in the xlsx file format that can be used to say “autofit columns on loading”. Auto-fitting of columns is something that Excel does at runtime when it has access to all of the worksheet information as well as the Windows functions for calculating display areas based on fonts and formatting.
It is a simulated method and may not be accurate in all cases.
It is based on the default font and font size of Calibri 11. It will not give accurate results for other fonts or font sizes.
The autofit() method won’t override a user defined column width set with set_column() or set_column_pixels() if it is greater than the autofit value. This allows the user to set a minimum width value for a column.
You can also call set_column() and set_column_pixels() after autofit() to override any of the calculated values.
There's also an example in the docs: https://xlsxwriter.readthedocs.io/example_autofit.html
The example's code:
#######################################################################
# copied from the docs
#######################################################################
from xlsxwriter.workbook import Workbook
workbook = Workbook("autofit.xlsx")
worksheet = workbook.add_worksheet()
# Write some worksheet data to demonstrate autofitting.
worksheet.write(0, 0, "Foo")
worksheet.write(1, 0, "Food")
worksheet.write(2, 0, "Foody")
worksheet.write(3, 0, "Froody")
worksheet.write(0, 1, 12345)
worksheet.write(1, 1, 12345678)
worksheet.write(2, 1, 12345)
worksheet.write(0, 2, "Some longer text")
worksheet.write(0, 3, "http://ww.google.com")
worksheet.write(1, 3, "https://github.com")
# Autofit the worksheet.
worksheet.autofit()
workbook.close()
win32com
solution is perfect. Thanks! – Cataplexy