zoukankan      html  css  js  c++  java
  • 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`

    至此则能正常导出表格。

  • 相关阅读:
    RK 清理后台所有历史App任务
    RK onConfigurationChanged ConfigChanges 设备状态的改变
    RK audio 拨号同时输出Speaker和USB音频
    RK 微信视频通话预览倒立
    Unity 笔记
    C# 泛型约束为枚举
    Unity Editor 扩展PropertyDrawer (属性的 Inspector )
    Unity Editor 笔记
    Unity 反转法线,在 Hierarchy 视图对象的快捷菜单中增加 Flip Mesh Normals(反转网格法线)项
    Blender 2.9 骨骼
  • 原文地址:https://www.cnblogs.com/wangyingblock/p/10412441.html
Copyright © 2011-2022 走看看