I am trying to create an Excel workbook where I can auto-set, or auto-adjust the widths of the columns before saving the workbook.
I have been reading the Python-Ex
This may be a little late, but I created a method that does this for the whole sheet at once. It's quick and gets the job done. The extra cushion param. is only needed if you think that the 256 calculation won't be accurate (if you have longer text fields).
from xlrd import *
from xlwt import *
def autoAdjustColumns(workbook, path, writerSheet, writerSheet_index, extraCushion):
readerSheet = open_workbook(path).sheet_by_index(writerSheet_index)
for row in range(readerSheet.nrows):
for column in range(readerSheet.ncols):
thisCell = readerSheet.cell(row, column)
neededWidth = int((1 + len(str(thisCell.value))) * 256)
if writerSheet.col(column).width < neededWidth:
writerSheet.col(column).width = neededWidth + extraCushion
workbook.save(path)