js Excel前端生成下载, Excel后端生成下载
Excel前端生成下载
import XLSX from 'xlsx'
function openDownloadDialog(url, saveName) {
if(typeof url == 'object' && url instanceof Blob)
{
url = URL.createObjectURL(url);
}
var aLink = document.createElement('a');
aLink.href = url;
aLink.download = saveName || '';
var event;
if(window.MouseEvent) event = new MouseEvent('click');
else
{
event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
aLink.dispatchEvent(event);
}
function sheet2blob(sheet, sheetName) {
sheetName = sheetName || 'sheet1';
var workbook = {
SheetNames: [sheetName],
Sheets: {}
};
workbook.Sheets[sheetName] = sheet;
var wopts = {
bookType: 'xlsx',
bookSST: false,
type: 'binary'
};
var wbout = XLSX.write(workbook, wopts);
var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
return blob;
}
function getexcel(dataSource, title){
let sheet = XLSX.utils.aoa_to_sheet(dataSource);
openDownloadDialog(sheet2blob(sheet), `${title}.xlsx`);
}
Excel后端生成下载
function delExcelBlob(data, title) {
let url = URL.createObjectURL(new Blob([data]))
let link = document.createElement('a',{type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})
link.style.display = 'none'
link.href = url
link.setAttribute('download', title)
document.body.appendChild(link)
link.click()
}