Excel下载不适用于MEAN栈应用程序
我想单击button时下载excel文件。
当我点击下载button时,我想用数据库中的dynamic数据创build一个Excel文件并下载它(注意:不想创build并将excel文件存储到物理path中,然后下载它)。
HTML代码
<button ng-click="exportData()" class="btn btn-sm btn-primary btn-create">Download</button>
控制器代码
$scope.exportData = function () { $http.get('/Getexcel').then(function (response) { }); };
服务器代码
const ExcelConfig = require('./public/Models/Schema/excel'); app.get('/Getexcel', ExcelConfig.getexceldata);
注意:ExcelConfig包含架构代码的path
excel.js代码
// Require library var xl = require('excel4node'); const tempfile = require('tempfile'); // Create a new instance of a Workbook class var wb = new xl.Workbook(); // Add Worksheets to the workbook var ws = wb.addWorksheet('MaterialFlowSheet'); // Create a reusable style var style = wb.createStyle({ font: { color: '#FF0800', size: 12 }, numberFormat: '$#,##0.00; ($#,##0.00); -' }); exports.getexceldata = (req, res) => { ws.cell(1, 1).string('BatchId').style(style); ws.cell(1, 2).string('Source').style(style); ws.column(2).setWidth(50); ws.row(1).setHeight(20); ws.cell(1, 3).string('Destination').style(style); ws.column(3).setWidth(50); ws.row(1).setHeight(20); ws.cell(1, 4).string('DistanceBetweenTwoBuilding').style(style); ws.column(4).setWidth(25); ws.row(1).setHeight(20); ws.cell(1, 5).string('SKU').style(style); ws.cell(1, 6).string('UOM').style(style); ws.cell(1, 7).string('QtyToBeDelivered').style(style); ws.column(7).setWidth(20); ws.row(1).setHeight(20); ws.cell(1, 8).string('CartType').style(style); wb.write('Excel.xlsx'); res.download('\Excel.xlsx'); };
我已经尝试过上面的示例文件下载。 所以当我点击下载button,文件不下载,而不是在UI中发生。 但是我正在下载如果我访问这个URL http://localhost:8080/Getexcel
。 任何人都可以通过点击下载button给解决scheme下载Excel文件?
您必须将回复作为文件发送
app.get('/spreadsheet', function(req, res, next) { res.setHeader('Content-disposition', `attachment;filename=data.xls`); res.setHeader('Content-type', 'application/vnd.ms-excel'); res.charset = 'UTF-8'; res.status(200).end(xls); });
也许是晚了,但是,鉴于你的服务器端代码是好的(我不是节点或快递的专家),你应该在请求中设置请求标题:
$scope.exportData = function () { $http.get('/Getexcel', {responseType: "arraybuffer"}). .... };
然后可能使用FileSaver来保存对文件的响应,就像这样
$scope.exportData = function () { $http.get('/Getexcel', {responseType: "arraybuffer"}) .success(function(response) { data = new Blob([response.data], {type: response.headers('content-type')}); FileSaver.saveAs(data, filename); }); };