文本流数据转文件(word,excel,zip 等)
写在前面
我们在开发项目的时候,不难遇到一些导出的功能。比如说:导出excel表格等等。
我在开发中就遇到了这么一个功能,将一些表格数据导出成一个excel表格,那么,这个应该怎么做呢?
写这篇博客一来是为了加强自己的记忆,毕竟好记性不如烂笔头嘛,嘿嘿。。。第二个方面呢,希望能和大家一起分享这个功能,希望能帮助到那些没有接触过这个功能的小伙伴。
话不多说,上菜咯
- 功能
点击导出全部数据,下载列表中的内容
- - 后台接口返回的内容
- - 在post请求中添加responseType: 'blob'
export function postFile2(url, params = {}, headers = {
'Content-Type': 'application/json; charset=utf-8'
}) {
return new Promise((resolve, reject) => {
http({
url,
data: params,
method: "post",
headers,
responseType: 'blob',
}).then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
})
}
这样我们就可以把文件流转换成blob文件
可以再控制台打印一下我们请求后台数据返回的参数
- 请求接口数据后
api.dataExport(params).then((res) => {
const reader = new FileReader();
reader.readAsDataURL(res.data); //res.data是我们需要下载的数据
reader.onload = (e) => {
let a = document.createElement("a"); //创建一个a标签
a.style.display = "none";
a.download = "data.xlsx"; // 文件名称及类型,可以变成.word .zip 等等
a.href = e.target.result;
const body = document.body;
document.body.appendChild(a); // 将a标签添加在body上
a.click(); // a标签上绑定一个点击事件
document.body.removeChild(a); // 下载完成之后删除a标签
};
});
最终效果
点击之后会将文件直接从浏览器上下载下来
附:
将二进制文件再通过浏览器预览,window.open()(只支持图片和pdf文件,其他格式文件只能下载)
- 另打开一个窗口预览pdf
function showPdf(base64Url) {
let pdfWindow = window.open("");
pdfWindow.document.write("<iframe width='100%' height='100%' src=" + base64Url+ "></iframe>");
pdfWindow.document.title = "PDF"
pdfWindow.document.close();
},
- 另打开一个窗口预览图片
function showImg (base64Url) { const img = new Image(); img.src = base64Url; const newWindow = window.open("", "_blank"); newWindow .document.write(img.outerHTML); newWindow .document.title = "图片"; newWindow .document.close(); }