繁体   English   中英

通过nodejs将mysql(sequelize)表数据导出到json

[英]Export mysql (sequelize) table data to json by nodejs

我有json数据,我想将其导出为data.xlsx。 例如

我在表上有一个导出按钮,如果用户单击该导出按钮,则此ng-click功能将起作用。

controllers.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包。

如果单击“导出”,该文件将下载到我的项目中。

但是我需要输出,当用户单击导出按钮时,应该在chrome左上角以及用户默认的下载目录中下载“ data.xlsx”文件。

您必须在res标头中设置参数。

您可以尝试以下操作:

var fields = ['firstName', 'email'];
                var csv = json2csv({ data: resp, fields: fields });
                res.set('Cache-Control', 'max-age=0, no-cache, must-revalidate, proxy-revalidate');
                res.set('Content-Type','application/force-download');
                res.set('Content-Type','application/octet-stream');
                res.set('Content-Type','application/download');
                res.set('Content-Disposition','attachment;filename=userList.csv');
                res.set('Content-Transfer-Encoding','binary');
                res.send(csv); 

因此,当您在浏览器中点击API时,它将询问SaveFile选项,如果用户单击“确定”,它将被下载到chrome的默认下载目录。

将文件保存在服务器中之后。 您需要发送文件名,以便可以从浏览器访问文件:

$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' });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM