上一篇文章“web2py grid 的csv导出优化excel中文乱码和表头label”已经充分优化了web2py的csv文件的中文导出功能,有些场景还需要导出xlsx格式的,那我们继续,优化web2py自带gluon文件下的sqlhtml.py文件:
1、pip安装
openpyxl库
pip install
openpyxl
2、在sqlhtml.py文件最后增加代码,就是新增xlsx的导出类
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.replace('"', '') for name in self.rows.colnames ] book = openpyxl.Workbook() sheet = book.active (sheet.title, _)= rows_colnames[0].split('.') #写lable表头 tables=[];fields=[];labels=[]; for col in rows_colnames: (t,f) = col.split('.') tables.append(t) fields.append(f) labels.append(str(self.rows.db[t][f].label)) sheet.append(labels) # list转为set,再转为list能实现list去重, # 字段来自多个表则为联查拼的表 if len((list(set(tables)))) > 1: field_len=len(fields) for row in self.rows: write_line = [row[tables[f]][fields[f]] for f in range(0,field_len)] sheet.append(write_line) else: for row in self.rows: write_line=[ row[f] for f in fields] sheet.append(write_line) s = StringIO() book.save(s) return s.getvalue()
3、找到 exportManager = dict(....)这里增加我们的导出类型:
exportManager = dict(
xlsx=(ExporterXLSX, 'XLSX文件导出', T('XLSX文件导出')),
........
)
4、OK了,打开你的grid组件: