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

后端 未结 6 1269
一向
一向 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:39

    I just implemented a wrapper class that tracks the widths of items as you enter them. It seems to work pretty well.

    import arial10
    
    class FitSheetWrapper(object):
        """Try to fit columns to max size of any entry.
        To use, wrap this around a worksheet returned from the 
        workbook's add_sheet method, like follows:
    
            sheet = FitSheetWrapper(book.add_sheet(sheet_name))
    
        The worksheet interface remains the same: this is a drop-in wrapper
        for auto-sizing columns.
        """
        def __init__(self, sheet):
            self.sheet = sheet
            self.widths = dict()
    
        def write(self, r, c, label='', *args, **kwargs):
            self.sheet.write(r, c, label, *args, **kwargs)
            width = arial10.fitwidth(label)
            if width > self.widths.get(c, 0):
                self.widths[c] = width
                self.sheet.col(c).width = width
    
        def __getattr__(self, attr):
            return getattr(self.sheet, attr)
    

    All the magic is in John Yeung's arial10 module. This has good widths for Arial 10, which is the default Excel font. If you want to write worksheets using other fonts, you'll need to change the fitwidth function, ideally taking into account the style argument passed to FitSheetWrapper.write.

提交回复
热议问题