• node简单实现excel文件下载


    1.利用csv格式兼容实现

    csv是一种利用','、' '、' '等分隔符存储的文本文件,excel可兼容打开,利用此原理,代码实现如下:

    app.use(route.get('/export', async ctx => {
    	ctx.res.setHeader('Content-Type', 'application/vnd.ms-execl');
    	ctx.res.setHeader("Content-Disposition", "attachment; filename=" + "answer_data.xlsx");
    
    	let arr = [{
    		"q": "问题1",
    		"answer": "答案1"
    	}]
    	//xls兼容csv
    	let content = '';
    	for (let i = 0, len = arr.length; i < len; i++) {
    		content += arr[i]['q'];
    		content += '	';
    		content += arr[i]['answer'];
    		content += '	';
    		content += '	
    ';
    	}
    	ctx.body = content;
    }));
    

    2.使用库文件

    excel是使用xml格式进行存储,在传输过程总是用zip进行压缩,具体可以查看sheet.js、excel-export源码实现,excel的xml格式具体可以见Introduction to Excel XML
    刚开始如引入export-excel来实现文件下载

        conf.stylesXmlFile = "styles.xml";
        conf.name = "sheeName";
        conf.cols = [{
            caption:'姓名',
            type:'string'
        }, {
            caption: '年龄',
            type: 'string'
        }];
        conf.rows = data;//data = [{name: '', age: ''}]
        let  result = nodeExcel.execute(conf);//const nodeExcel = require('export-excel');
        ctx.res.setHeader('Content-Type', 'application/vnd.openxmlformats');
        ctx.res.setHeader("Content-Disposition", "attachment; filename=" + "demo.xlsx");
    

    但是发现其源码中引入的collection模块给Array.portotype添加了find方法,与es6实现的find方式冲突,因此放弃使用,选择了js-xlsx

  • 相关阅读:
    OpenStack网卡桥接问题
    Linux DD添加swap分区
    OpenStack KVM嵌套虚拟化的配置
    OpenStack KVM嵌套虚拟化的配置
    received packet with own address as source address
    mysql ERROR 1040 (08004): Too many connections
    openstack以其他tenant用户创建实例
    OpenStack Controller HA (3)
    OpenStack Controller HA (2)
    OpenStack controller HA
  • 原文地址:https://www.cnblogs.com/zsblogs/p/8908662.html
Copyright © 2020-2023  润新知