1.有请求接口返回arraybuffer类型的数据(npm: jszip, file-saver)
const zip = new JSZip();
let promises = [];// 所有下载请求的数组集合
const getFile = url => { // 一个http get请求
return new Promise((resolve, reject) => {
Vue.http.get(url, {responseType: 'arraybuffer'}).then(data => {
resolve(data.data);
}).catch(error => {
reject(error.toString());
});
});
};
downloadData.forEach(item => {
let promise;
promise = getFile(`XXX/${item.id}/download`).then(data => {
zip.file(`${item.name}.pdf`, data, {binary: true}); // 逐个添加文件,需要后缀名,pdf或xlsx都可
});
promises.push(promise);// 逐个添加请求
});
Promise.all(promises).then(async () => {
await zip.generateAsync({ type: 'blob' }).then(content => {
// 生成二进制流
FileSaver.saveAs(content, 'xxx.zip'); // 利用file-saver保存文件 自定义文件名
});
});
2.无接口请求 / 自己组装的数据转化为Excel表格(npm: xlsx, jszip, file-saver)
getCharCol (n) {
let temCol = '', s = '', m = 0;
while (n > 0) {
m = n % 26 + 1;
s = String.fromCharCode(m + 64) + s;
n = (n - m) / 26;
}
return s;
}
for (let i = 0; i < this.selected.length; i ++) {
/* 先得到目前下标的downloadData */
var keys = Object.keys(downloadData[0]);
var content = {};
// 把json格式的数据转为excel的行列形式
var sheetsData = downloadData.map(function (item, rowIndex) {
return keys.map(function (key, columnIndex) {
return Object.assign({}, {
value: item[key],
position: (columnIndex > 25 ? this.getCharCol(columnIndex) : String.fromCharCode(65 + columnIndex)) + (rowIndex + 1),
});
});
}).reduce(function (prev, next) {
return prev.concat(next);
});
sheetsData.forEach(function (item, index) {
content[item.position] = { v: item.value };
});
var coordinate = Object.keys(content);
var workBook = {
SheetNames: ['main'],
Sheets: {
'main': Object.assign({}, content, { '!ref': coordinate[0] + ':' + coordinate[coordinate.length - 1] }),
}
};
var excelData = XLSX.write(workBook, { bookType: 'xlsx', bookSST: false, type: 'binary' });
var blob = new Blob([this.string2ArrayBuffer(excelData)], { type: '' });
zip.file(`xxxx.xlsx`, blob, {binary: true});
}
await zip.generateAsync({type:'blob'}).then(function(content) {
FileSaver.saveAs(content, 'xxx.zip');
});