【发布时间】:2017-11-06 05:38:46
【问题描述】:
单击按钮时我想下载 excel 文件。
当我点击下载按钮时,我想用数据库中的动态数据创建一个 Excel 文件并下载它(注意:不要创建并存储 excel 文件到物理路径然后下载它)。
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 包含架构代码的路径
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');
};
我已尝试下载上述示例文件。因此,当我单击“下载”按钮时,该文件没有下载,而是 UI 中没有发生任何事情。但如果我访问此 URL http://localhost:8080/Getexcel,我将被下载。
任何人都可以通过单击“下载”按钮提供下载 excel 文件的解决方案吗?
【问题讨论】:
-
嗨,大卫,你能找到我点击按钮时没有下载 excel 文件的原因吗
-
我们可以看一个服务器响应的例子吗?它是一个字节数组吗?如果您从服务器返回原始数据,您可能需要添加到标头调用(角度方面)
arrayBuffer。 -
res.download('\Excel.xlsx');/ -
我认为错误在于处理客户端代码中的下载... ajax 调用不会为您保存文件。如果您需要解决这个问题,您可以清楚地找到我;-)