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

  • 相关阅读:
    npm 发包流程
    iframe嵌入第三方视频链接自动播放
    微信小程序 接入腾讯地图的两种写法
    微信小程序 生命周期
    css 传送阵
    微信小程序 音频播放器
    微信小程序 mpvue 使用vant-weapp
    微信小程序 使用mpvue
    ajax
    布局问题
  • 原文地址:https://www.cnblogs.com/zsblogs/p/8908662.html
Copyright © 2011-2022 走看看