前端:
downLoad() {
let url= url?id=${idParam}`
this.$axios({
url: url,
method: "get",
responseType: "blob" //服务器返回的数据类型
})
.then(res => {
//流的转储属于浅拷贝
const content = res.data;
const blob = new Blob([content]); //构造一个blob对象来处理数据
const fileName="文件名.xls" //excel文件
//const fileName="文件名.xls" //压缩包文件
//对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
//IE10以上支持blob但是依然不支持download
if ("download" in document.createElement("a")) {
//支持a标签download的浏览器
const link = document.createElement("a"); //创建a标签
link.download = fileName; //a标签添加属性
link.style.display = "none";
link.href = URL.createObjectURL(blob);
document.body.appendChild(link);
link.click(); //执行下载
URL.revokeObjectURL(link.href); //释放url
document.body.removeChild(link); //释放标签
} else {
//其他浏览器
navigator.msSaveBlob(blob, fileName);
}
})
.catch(err => {
console.log(err);
this.$message.error("下载文件失败");
});
},
后端:
后端采用Easypoi技术,相关pom依赖请自行查阅官方文档,excel采用excel模板导出Easypoi官网
@ApiOperation(value = "根据id取得详细信息", notes = "")
@RequestMapping(value = "/singleexcel", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public void excelsingle( HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取id
String id = request.getParameter("id");
if (id==null){
return;
}
//输出zip
// response.setHeader("content-Type", "application/octet-stream");
//输出excel
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("zhangsan", "UTF-8"));
response.setCharacterEncoding("UTF-8");
//excel模板业务处理
//获取对应的excel模板
TemplateExportParams params = new TemplateExportParams(
"excel/模板.xls");
JpAskStatisticsModel model = this.jpAskStatisticsService.get(Long.parseLong(id));
HashMap<String, Object> map = new HashMap<String, Object>();
//easypoi 模板业务处理
map("excel对应字段",数据)
OutputStream out=response.getOutputStream();
workbook.write(out);
//导出zip压缩包需要额外添加如下内容
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
//转化zip的字节流
HashMap<String, byte[]> excelMaps = new HashMap<>();
byte[ ] bytes = baos.toByteArray();
for(i=0,i<n,i++){
excelMaps.put(excel的文件名+".xls",bytes);
}
ZipUtils.downloadZipForByteMore(response.getOutputStream(),excelMaps);
}
package com.dhc.leapower.business.mobilecenter.mobileApp.utils;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.springframework.util.StreamUtils.BUFFER_SIZE;
public class ZipUtils {
/**
* 传入文件file
* @param outputStream
* @param fileList
*/
public static void downloadZipForFiles(OutputStream outputStream, List<File> fileList){
ZipOutputStream zipOutputStream = null;
try {
zipOutputStream = new ZipOutputStream(outputStream);
for (File file : fileList) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
byte[] buf = new byte[BUFFER_SIZE];
int len;
FileInputStream in = new FileInputStream(file);
while ((len = in.read(buf)) != -1) {
zipOutputStream.write(buf, 0, len);
zipOutputStream.flush();
}
}
zipOutputStream.flush();
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
try {
if (zipOutputStream != null ) {
zipOutputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 传入文件的 byte[]
* Map<String,byte[]> fileBufMap key是文件名(包含后缀),value是文件的byte[]
* @param outputStream
* @param fileBufMap
*/
public static void downloadZipForByteMore(OutputStream outputStream,Map<String,byte[]> fileBufMap) {
ZipOutputStream zipOutputStream = null;
try {
zipOutputStream = new ZipOutputStream(outputStream);
for (String fileName:fileBufMap.keySet()){
ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.putNextEntry(zipEntry);
if (Objects.nonNull(fileBufMap.get(fileName))){
byte[] fileBytes = fileBufMap.get(fileName);
zipOutputStream.write(fileBytes);
zipOutputStream.flush();
}
}
zipOutputStream.flush();
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭流
try {
if (zipOutputStream != null ) {
zipOutputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 返回zip包的 byte[]
*
* @param fileBufMap
* @return
*/
public static byte[] getZipForByteMore(Map<String,byte[]> fileBufMap) {
ByteArrayOutputStream totalZipBytes = null;
ZipOutputStream zipOutputStream = null;
try {
totalZipBytes = new ByteArrayOutputStream();
zipOutputStream = new ZipOutputStream(totalZipBytes);
for (String fileName:fileBufMap.keySet()){
ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.putNextEntry(zipEntry);
if (Objects.nonNull(fileBufMap.get(fileName))){
byte[] fileBytes = fileBufMap.get(fileName);
zipOutputStream.write(fileBytes);
zipOutputStream.flush();
}
}
zipOutputStream.close();
byte[] bytes = totalZipBytes.toByteArray();
// 关闭流
totalZipBytes.close();
return bytes;
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
try {
if (totalZipBytes != null) {
totalZipBytes.close();
}
if (zipOutputStream != null) {
zipOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}