前端调用后端的接口实现excel文件下载(下载Blod文件)(附带时间格式处理方法)
下载Blod文件,导出处理文件流,下载文件,前端导出文件
·
下载Blod文件(导出处理文件流)
// data表示后端返回的文件流
// fileName表示需要导出的文件名 --> 如果没有入参,则文件名默认为当前时间
export function exportExcelBlod(data,fileName){
if(!data) { // 如果没有返回结果,直接return出去
return;
};
const name = fileName || `${formatDataTime('yyyyMMDDHHmmss')}.xlsx`;
const blob = new Blob([data], { // 取相应回来的数据
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;'
});
const href = window.URL.createObjectURL(blob);
const downloadElement = document.createElement('a') // 创建下载链接
downloadElement.style.display = 'none';
downloadElement.href = href;
downloadElement.download = name; //命名文件名
document.body.appendChild(downloadElement); //添加
// 兼容触发click a标签
const evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true);
downloadElement.dispatchEvent(evt);
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(blobUrl);
}
// 上文用到的时间格式处理方法
/**
* 日期对象转换为指定格式的字符串
* @param formatStr 日期格式,接收需要的时间格式,如果为空则默认 yyyy-MM-dd HH:mm:ss
* @param date Date日期对象, 如果缺省,则为当前时间
*
* YYYY/yyyy/YY/yy 表示年份
* MM/M 月份
* W/w 星期
* dd/DD/d/D 日期
* hh/HH/h/H 时间
* mm/m 分钟
* ss/SS/s/S 秒
* @return string 指定格式的时间字符串
*/
export function formatDataTime(formatStr, date){
formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
date = arguments[1] || new Date();
var str = formatStr;
var Week = ['日','一','二','三','四','五','六'];
str=str.replace(/yyyy|YYYY/,date.getFullYear());
str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100));
str=str.replace(/MM/,date.getMonth()>9?(date.getMonth() + 1):'0' + (date.getMonth() + 1));
str=str.replace(/M/g,date.getMonth());
str=str.replace(/w|W/g,Week[date.getDay()]);
str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate());
str=str.replace(/d|D/g,date.getDate());
str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours());
str=str.replace(/h|H/g,date.getHours());
str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes());
str=str.replace(/m/g,date.getMinutes());
str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds());
str=str.replace(/s|S/g,date.getSeconds());
return str;
}
更多推荐
已为社区贡献1条内容
所有评论(0)