Python项目开发公用方法--excel生成方法

在实际开发中,我们有时会遇到数据导出的需求。一般的,导出的文件格式为Excel形式。

那么,excel的生成就适合抽离出一个独立的公用方法来实现:

 def generate_excel(excel_name, title_list, properties, data):
"""
生成指定的excel文件,并返回文件的路径,文件保存在static/files/excels下,并自动追加时间戳
:param excel_name: 文件名, 注意不要带文件类型后缀
:param title_list: 标题
:param properties: 对应的属性名,方法按照".property_name"的方式获取值
:param data: 数据,建议为query_set
:return: 生成文件的全路径
"""
now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
workbook = xlsxwriter.Workbook("{}/{}{}.xlsx".format(EXCEL_DIR, excel_name, now))
worksheet = workbook.add_worksheet(excel_name)
worksheet.set_first_sheet()
for i in range(len(title_list)):
worksheet.set_column('{}:{}'.format(chr(65 + i), chr(66 + i)), 20) excel_format = workbook.add_format()
excel_format.set_border(1)
excel_format.set_align('center')
excel_format.set_text_wrap() format_title = workbook.add_format()
format_title.set_border(1)
format_title.set_bg_color('#cccccc')
format_title.set_align('center')
format_title.set_bold() # 表头
worksheet.write_row('A1', title_list, format_title)
i = 2
for datum in data:
location = 'A' + str(i)
worksheet.write_row(location, [eval("datum.{}".format(key)) for key in properties], excel_format)
i += 1 workbook.close()
file_path = "{}/{}{}.xlsx".format(EXCEL_DIR, excel_name, now)
if file_path:
os.chmod(file_path, 0777)
return file_path

该方法接收必要的数据生成excel,返回最终的路径。

上一篇:跟我一起写Makefile


下一篇:[转载]C#读取Excel几种方法的体会