使用exceljs在node.js中下载Excel文件无法正常工作

3

你好,我是一个新手,正在学习MEAN技术栈。

当我点击导出按钮时,我希望能够下载Excel文件。

我使用了这个参考链接来下载Excel文件:https://www.npmjs.com/package/exceljs

HTML页面

<button ng-click="exportData()" class="btn btn-sm btn-primary btn-create">Export</button>

我的控制器
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies", "ngRoute"]);
        app.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
        }]);

app.controller('ManageMaterialFlowController', ['$http', '$scope', '$window', '$filter', '$notify', '$cookieStore',  'StoreService',
 function ($http, $scope, $window, $filter, $notify, $cookieStore, StoreService, $routeProvider) {



     //download excel file button click

     $scope.exportData = function () {

         router.get('/download', function (req, res) {

             try {
                 var Excel = require('exceljs');
                 var workbook = new Excel.Workbook();
                 var options = {
                     filename: './Excel.xlsx',
                     useStyles: true,
                     useSharedStrings: true
                 };
                 var workbook = new Excel.Workbook();
                 var worksheet = workbook.addWorksheet('My Sheet');

                 worksheet.columns = [
                     { header: 'Id', key: 'id', width: 10 },
                     { header: 'Name', key: 'name', width: 32 },
                     { header: 'D.O.B.', key: 'DOB', width: 10 }
                 ];
                 worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) });
                 worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) });

                 var tempFilePath = tempfile('.xlsx');
                 workbook.xlsx.writeFile(tempFilePath).then(function () {
                     console.log('file is written');
                     res.sendFile(tempFilePath, function (err) {
                         console.log('---------- error downloading file: ' + err);
                     });
                 });
             } catch (err) {
                 console.log('OOOOOOO this is the error: ' + err);
             }

         });

     };
}

我不知道如何做这个。通过点击按钮下载Excel文件的方式是否正确?

当我点击按钮时,出现“router未定义”的错误。有人能解决我的问题吗?


对于您的服务器代码,您可以使用当前已有的相同代码并将其存储在一个文件夹中,然后对于下载,您可以参考这里 - Kanagu
exportData() 函数的定义是什么? - Rupali
嗨,Rupali,exportData()是ng-click函数。如果我点击按钮,它将下载Excel文件。 - Vinoth
@Vinoth 我认为你对 node.js 代码和 angular 代码有些混淆了。控制器是一个 .js 文件。你直接复制了 excel 的代码,但并没有理解它的作用。路由器是 express 路由器的一个变量。var express = require('express'); var router = express.Router(); - codeinprogress
嗨,code in progress,我已经创建了我的文件,但不知道如何下载该文件,你能给我一些例子吗? - Vinoth
显示剩余2条评论
2个回答

2

请勿使用

workbook.xlsx.writeFile()

writeFile()方法用于将文件保存到硬盘。

相反,使用write()方法。该方法将文件写入流中。

res对象是一个可写流。因此你可以这样使用。

workbook.xlsx.write(res)

而且你不需要调用它

res.sendFile(tempFilePath) 

因为您已经将 Excel 文件管道化到 res 对象中,所以代码如下:
workbook.xlsx.write(res).then(function () {
    res.status(200).end();
});

最后,您应该在res对象上添加https头。
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

res.setHeader("Content-Disposition", "attachment; filename=YOUR_FILENAME.xlsx");

Content-Type通知Web浏览器数据类型是什么。

Content-Disposition通知Web浏览器该数据将保存到硬盘中。

最终代码在这里。


res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

res.setHeader("Content-Disposition", "attachment; filename=Rep1ort.xlsx");

workbook.xlsx.write(res).then(function () {
    res.status(200).end();
});

当您在ReactJS上收到响应时,如何下载文件。 - hu7sy
axios.get(myRoute, { responseType: 'arraybuffer' }) .then(response => { const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); FileDownload(blob, `file.xlsx`); // npm " js-file-download" 负责为用户下载文件 }); 在 React.js 中,当文件下载后发现文件损坏。 - hu7sy

1
我参考了这个链接来写数据到Excel表格中。

https://www.npmjs.com/package/exceljs

为了下载Excel表格,我使用了以下代码来下载Excel表格。

 var fileName = "Task" + '_Template.xlsx';
    var tempFilePath = __dirname + "\\public\\template\\" + fileName;
    workbook.xlsx.writeFile(tempFilePath).then(function () {
        res.send(fileName);
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接