后台表格导出excel
1、传入导出条件,调用后端接口,获取到导出数据,以及文件名称和文件路径。 2、调用以下方法,传入上述接口得到的数据以及文件名称。
downloadXlsx(res, filename) {
if ("download" in document.createElement("a")) {
const elink = document.createElement("a");
elink.download = filename;
elink.style.display = "none";
elink.href = res.file.url;
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);
document.body.removeChild(elink);
} else {
navigator.msSaveBlob(res, filename);
}
}
导出pdf的方法
通过canvas实现导出pdf;
export function exportPdf(
dom,
name,
backgroundColor = "#f6f6f6",
scale = 3.15
) {
return html2canvas(dom, {
backgroundColor,
width: dom.offsetWidth,
height: dom.offsetHeight + 200,
scale,
useCORS: true
}).then(function(canvas) {
let width = canvas.style && canvas.style.width,
height = canvas.style && canvas.style.height;
let contentWidth = width.replace(/px/, "");
let contentHeight = height.replace(/px/, "");
let context = canvas.getContext("2d");
context.webkitImageSmoothingEnabled = false;
context.mozImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
let imageData = context.getImageData(0, 0, contentWidth, contentHeight);
for (let i = 0; i < imageData.data.length; i += 4) {
if (imageData.data[i + 3] === 0) {
imageData.data[i] = 246;
imageData.data[i + 1] = 246;
imageData.data[i + 2] = 246;
imageData.data[i + 3] = 246;
}
}
context.putImageData(imageData, 0, 0);
var imgData = canvas.toDataURL("image/jpeg", 1.0);
let img = new Image();
img.src = imgData;
img.onload = function() {
let doc;
if (contentWidth > contentHeight) {
doc = new JsPDF("l", "pt", [contentWidth, contentHeight]);
} else {
doc = new JsPDF("p", "pt", [contentWidth, contentHeight]);
}
doc.addImage(imgData, "jpeg", 0, 0, contentWidth, contentHeight);
doc.save((name || new Date().getTime()) + ".pdf");
};
});
}
导出img
细节方面,根据需要自己调整,我就不仔细说了。
export function exportImg(dom, name) {
html2canvas(dom, {
backgroundColor: "#fff",
width: dom.offsetWidth,
height: dom.offsetHeight + 10,
scale: 3.125,
useCORS: true
}).then(function(image) {
if (image.msToBlob) {
navigator.msSaveBlob(image.msToBlob(), `${name || Date.now()}.png`);
} else {
let url = image.toDataURL("image/png", 1.0);
let $a = document.createElement("a");
let type = "png";
$a.href = url;
$a.target = "_blank";
$a.download = name || "未命名" + "." + type;
document.body.appendChild($a);
$a.click();
document.body.removeChild($a);
}
});
}
最近隔离刚好有空,总结一下之前项目中写过的功能。大家有什么问题也可以留言,大家可以一起想办法解决。
|