我有 json 数据,我想将其导出为 data.xlsx。例如
我的表格中有一个导出按钮,如果用户单击该导出按钮,则此 ng-click 功能将起作用。
Controller .js:
$scope.exportDataXlsx = function () {
var json = $scope.contacts;
console.log(json);
$http.post('/api/exportcontactsxlsx', json).then(function (response) {
$state.reload();
toastr.success("exported successfully!");
});
};
我的API代码:
exports.exportContactsXlsx = function (req, res) {
var data = req.body;
var xls = json2xls(data);
fs.writeFileSync('data.xlsx', xls, 'binary');
}
我正在使用名为 jsonexport 的 npm 包。
如果我单击导出,文件将下载到我的项目中。
但是我需要输出,当用户单击导出按钮时,“data.xlsx”文件应该下载到 chrome 左 Angular 和用户默认下载目录中。
最佳答案
将文件保存到服务器后。您需要的是发送文件名,以便您可以从浏览器访问它:
$scope.exportDataXlsx = function () {
var json = $scope.contacts;
console.log(json);
$http.post('/api/exportcontactsxlsx', json).then(function (response) {
downloadFile(response.fileName) // make sure response.fileName has the file name
$state.reload();
toastr.success("exported successfully!");
});
};
function downloadFile(name) {
var link = document.createElement('a');
link.download = name;
link.href = '/files/' + name;
link.click();
}
服务器:
// in app.js, to serve your files as static files
app.use("/files", express.static(path.join(__dirname, 'files')));
// send the the name of your file to the client
exports.exportContactsXlsx = function (req, res) {
var data = req.body;
var xls = json2xls(data);
fs.writeFileSync(path.join(__dirname,'../files/data.xlsx'), xls, 'binary');
//changed the directory
res.json({ fileName: 'data.xlsx' });
}
关于javascript - 通过nodejs将mysql(sequelize)表数据导出为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48206414/