javascript - 通过nodejs将mysql(sequelize)表数据导出为json

标签 javascript mysql angularjs json node.js

我有 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/

相关文章:

javascript - 向服务器发送最小数据的最佳协议(protocol)是什么

java - JDBC:共享连接或使用连接池

php - 如何轻松确定生日的年龄? (php)

javascript - 相同的指令具有不同的消息 - angularJS

angularjs - 在 angularJS 服务中收到新项目时重新加载 ionic ng-repeat 列表

javascript - 如何在两行后添加省略号?

javascript - 如何将 data.key --> element.id 绑定(bind)到 d3js 中的现有标记上?

javascript - Javascript 是否比 O'Reilly Javascript Patterns 一书中提到的闭包和匿名函数更好?

javascript - 将鼠标悬停在按钮上时显示图像

php - 我可以将 'mysql_query' 的各个字段转换为数组吗?