SQLFORM.grid add MS Excel xlsx format export

15 views
Skip to first unread message

Tao Lee (XJSLKR)

unread,
Sep 28, 2022, 2:16:43 AMSep 28
to web2py-users
1、pip install openpyxl

2、at the end of sqlhtml.py ,add a new export class:

class ExporterXLSX(ExportClass):
    label = 'XLSX'
    file_ext = "xlsx"
    content_type = ".xlsx"
    def __init__(self, rows):
        ExportClass.__init__(self, rows)

    def export(self):
        import openpyxl
        if len(self.rows) == 0:
            return 'empty rows-table'
        rows_colnames= [name.translate(None,'"') for name in self.rows.colnames ]
        (table_name, _)= rows_colnames[0].split('.')
        book = openpyxl.Workbook()
        sheet = book.active
        sheet.title = table_name

        fields=[]; labels=[]
        for col in rows_colnames:
            (t,f) = col.split('.')
            fields.append(f)
            labels.append( self.rows.db[t][f].label )
        sheet.append(labels)

        for row in self.rows:
             llist=[ row[f]  for f in fields]
             sheet.append(llist)

        s = StringIO()
        book.save(s)
        return s.getvalue()

3、find  exportManager = dict(....) add a new exportType, like:

exportManager = dict(
    xlsx=(ExporterXLSX, 'XLSX file ', T(' XLSX file export ')),  
    ........)

4、restart your web2py it works.

Reply all
Reply to author
Forward
0 new messages