node簡單實現excel文件下載

1.利用csv格式兼容實現

csv是一種利用','、'\t'、'\n'等分隔符存儲的文本文件,excel可兼容打開,利用此原理,代碼實現以下:javascript

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 += '\t';
        content += arr[i]['answer'];
        content += '\t';
        content += '\t\n';
    }
    ctx.body = content;
}));

2.使用庫文件

excel是使用xml格式進行存儲,在傳輸過程老是用zip進行壓縮,具體能夠查看sheet.js、excel-export源碼實現,excel的xml格式具體能夠見Introduction to Excel XML
剛開始如引入export-excel來實現文件下載java

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-xlsxnode

相關文章
相關標籤/搜索