import xlsxwriter
class ExportFile:
def __init__(self, filename, obj_list, keys_list, verbose_list):
"""
:param filename: 文件名
:param obj_list: 对象
:param keys_list: key对应对象的每一个字段
:param verbose_list: value对应verbose_name excel 第一行的每列表示
"""
self.filename = filename
self.obj_list = obj_list
self.wb = xlsxwriter.Workbook(filename)
self.ws = self.wb.add_worksheet('sheet1')
self.verbose_list = verbose_list
self.key_list = keys_list
def create_xlsx(self, other=None):
self.create_row()
if other is not None:
self.create_other_row()
self.wb.close()
def create_row(self):
for col_1 in range(len(self.verbose_list)):
self.ws.write(1, col_1, self.verbose_list[col_1])
def create_other_row(self):
row_ = 2
for obj in self.obj_list:
# obj = ['ytt', 26]
for x in range(len(self.key_list)):
self.ws.write(row_, x, obj[x])
row_ += 1
filename = 'od人员表.xlsx'
obj_list = [['ytt', 26], ['lsp', 27], ['jas', 27]]
verbose_list = ['姓名', '年龄']
key_list = ['name', 'age']
xlsx = ExportFile(filename, obj_list, key_list, verbose_list)
xlsx.create_xlsx()
create_xlsx方法为主方法,other为None时则只生成字段的表格,即只有一行;反之根据obj_list的数据产生相应的表格数据。