Python xlwt - accessing existing cell content, auto-adjust column width

后端 未结 6 1278
一向
一向 2020-11-29 03:17

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

6条回答
  •  天涯浪人
    2020-11-29 03:35

    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)
    

提交回复
热议问题