Changeset 2f78be1 in rattail


Ignore:
Timestamp:
06/13/18 20:59:35 (2 years ago)
Author:
Lance Edgar <lance@…>
Branches:
master
Children:
1d8ca3b
Parents:
790c411
Message:

Add ExcelWriter.auto_resize() method

tries to auto-size all column widths according to simple data length

File:
1 edited

Legend:

Unmodified
Added
Removed
  • rattail/excel.py

    r790c411 r2f78be1  
    2929import datetime
    3030
     31import six
    3132import xlrd
    3233from xlrd.xldate import xldate_as_tuple
     
    3435import openpyxl
    3536from openpyxl.styles import Font, PatternFill
     37from openpyxl.cell.cell import get_column_letter
    3638
    3739from rattail.util import progress_loop
     
    137139        self.sheet.auto_filter.ref = cellrange
    138140
     141    def auto_resize(self):
     142        """
     143        (Try to) Auto-resize all data columns.
     144        """
     145        # calculate desired column widths
     146        column_widths = []
     147        for i in range(self.sheet.max_column):
     148            colwidth = 0
     149            for j in range(self.sheet.max_row):
     150                width = len(six.text_type(self.sheet.cell(j + 1, i + 1).value))
     151                if width > colwidth:
     152                    colwidth = width
     153            column_widths.append(colwidth or 5)
     154
     155        # resize columns
     156        for i, width in enumerate(column_widths, 1):
     157            self.sheet.column_dimensions[get_column_letter(i)].width = width + 3
     158
    139159    def save(self):
    140160        self.book.save(self.path)
Note: See TracChangeset for help on using the changeset viewer.