1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| app.post('/list/export', (req,res)=>{ const data = getDataFromDB(req.body) generateExcel(results, ()=>{ res.download(path.join(__dirname,'list.xlsx')); }) }, err => { res.json(err) }) })
const columns = [ { header: 'ID', key: 'id', width: 32 }, { header: 'Name', key: 'name', width: 32 }]; const generateExcel = function(data, callback){ const excel = require('exceljs'); // create excel workbook var options = { filename:path.join(__dirname, 'list.xlsx'), useStyles: true, useSharedStrings: true }; const workbook = new excel.stream.xlsx.WorkbookWriter(options); workbook.creator = 'QQs'; workbook.created = new Date(); workbook.modified = new Date(); // views workbook.views = [ { x: 0, y: 0, width: 10000, height: 20000, firstSheet: 0, activeTab: 1, visibility: 'visible' } ] // add worksheet const sheet = workbook.addWorksheet('List'); // define columns sheet.columns = columns; // add rows /* 数据量大的情况下考虑到nodejs内存分配瓶颈 *应限制每次select的条数分批addRow并且Row.commit */ data.forEach(record => { const row = record; // TODO data convertor sheet.addRow(row).commit(); }); sheet.commit(); workbook.commit().then(callback); }
|