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`

至此则能正常导出表格。

转载于:https://www.cnblogs.com/wangyingblock/p/10412441.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值