嗨,我是MEAN Stack的新手。
我想在单击导出按钮时下载 excel 文件。
我正在使用此参考链接下载 excel 文件:https://www.npmjs.com/package/exceljs
网页
页面
<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文件的正确方法。
当我单击按钮时,我得到路由器未定义错误。 任何人都可以解决我的问题吗?
不要使用
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");
内容类型通知 Web 浏览器数据类型是什么。
内容处置通知 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();
});
我引用此链接将数据发送到 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);
});