各种包对比介绍:https://www.cnblogs.com/sky6699/p/12738930.html

    1. const router = require('koa-router')();
    2. const nodeExcel = require('excel-export');
    3. const fs = require('fs');
    4. const path = require('path');
    5. const readData = (path) => {
    6. return new Promise(function (resolve, reject) {
    7. fs.readFile(path, function (err, data) {
    8. if (err) {
    9. reject(err);//文件存在返回true
    10. } else {
    11. resolve(data);//文件不存在,这里会抛出异常
    12. }
    13. });
    14. }).then(function (data) {
    15. console.log(data);
    16. return data;
    17. }, function (err) {
    18. console.log(err);
    19. return err;
    20. });
    21. };
    22. router.post('/exportExcel', async (ctx, next) => {
    23. const conf = {};
    24. conf.name = "exportTest";
    25. // cols可以为设置列类型的:caption为表头,type为列数据类型,beforeCellWrite可以在填充之前对数据进行逻辑处理,width可以定义列宽
    26. // excel-export提供了4种类型的数据格式,number,bool,date,默认string
    27. conf.cols = [{
    28. caption: '表头1',
    29. type: 'string',
    30. // beforeCellWrite: function (row, cellData) {
    31. // return cellData.toUpperCase();
    32. // },
    33. // width: 28
    34. }, {
    35. caption: '表头2',
    36. type: 'number',
    37. }, {
    38. caption: '表头3',
    39. type: 'bool',
    40. }, {
    41. caption: '表头4',
    42. type: 'date',
    43. }, {
    44. caption: '表头5',
    45. type: 'string',
    46. }, {
    47. caption: '表头6',
    48. type: 'string',
    49. }];
    50. // 行数据
    51. conf.rows = [
    52. ['content1', 1, true, (new Date(Date.UTC(2013, 4, 1))).oaDate(), '55', '66'], // 这里是value组成的数组
    53. ['content2', 2, true, (new Date(Date.UTC(2013, 4, 1))).oaDate(), '55', '66'],
    54. ['content3', 3, false, (new Date(Date.UTC(2013, 4, 1))).oaDate(), '55', '66'],
    55. ];
    56. var result = nodeExcel.execute(conf);
    57. ctx.set('Content-Type', 'application/vnd.openxmlformats');
    58. ctx.set("Content-Disposition", "attachment; filename=" + "Report.xlsx");
    59. fs.writeFile(path.join(__dirname, '../files/', 'log.xlsx'), result, { encoding: 'binary' }, function (err) {
    60. if (err) { console.log('写入错误'); }
    61. })
    62. let data = readData(path.join(__dirname, '../files/', 'log.xlsx'));
    63. ctx.body = data;
    64. });
    65. module.exports = router;