python表格导出--xlwt的使用

xlwt可以用来导出excel表,下面介绍一下它的用法:

1. 安装xlwt模块

pip install xlwt

2. 使用xlwt模块:后端接口编写

import xlwt

#导出表格接口
def export_excel(request):
    response = {}
    if os.path.exists('home_application/api/config/download/hosts.xls'):
        os.remove('home_application/api/config/download/hosts.xls')
    # 创建表格,默认字符编码为utf-8
    wb = xlwt.Workbook(encoding='utf-8')
    # 在当前表中创建工作簿,test为工作簿名称
    LST_test = wb.add_sheet('test', 'cell_overwrite_ok=True')
    # 设置列宽, 3为列的数目, 12为列的宽度, 100为固定值
    for i in range(3):
        LST_test.col(i).width = 80 * 100
    # 设置表头
     LST_test.write(0, 0, '姓名', xlwt.easyxf('font: height 240, colour_index red,'))  # 列名
     LST_test.write(0, 1, '年龄', xlwt.easyxf('font: height 240, colour_index red,'))
     LST_test.write(0, 2, '性别', xlwt.easyxf('font: height 240, colour_index red,'))
     #向单元格写入内容
     LST_test.write(1, 0, 'wwww')
     LST_test.write(1, 1, 'wwww')
     LST_test.write(1, 2, 'wwww')
     wb.save('home_application/api/config/download/hosts.xls')
     file = open('home_application/api/config/download/hosts.xls', 'rb')
     response = FileResponse(file)
     response['Content-Type'] = 'application/octet-stream'
     response['Content-Disposition'] = 'attachment;filename="hosts.xls"'

     return response

如果按照正常的调用接口的方法来调用此接口,则可在download文件夹中生成hosts.xls文件,但无法下载到本地电脑中。若想下载到本地则需要在前端做些操作。

 

3. 使用xlwt模块:前端接口调用

<a :href="downUrl" class="btn btn-default">导出表格</a>
downUrl = `xxx/export_excel?key=value`

至此则能正常导出表格。

posted @ 2019-02-28 10:01  yingzi__block  阅读(830)  评论(0编辑  收藏  举报