后端代碼
public void exportExcel(@RequestParam(required = true) String Id, HttpServletResponse response,
HttpServletRequest request) {
String msg ="";
try {
Dto.setId(Id);
List<HashMap<String, Object>> list = tbsMainInfoService.exportExcel(Dto);
//文件名稱
String filename = "導出目錄";
String agent = request.getHeader("User-Agent");
String filenameEncoder = "";
if (agent.contains("MSIE")) {
// IE瀏覽器
filenameEncoder = URLEncoder.encode(filename, "utf-8");
filenameEncoder = filenameEncoder.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐瀏覽器
BASE64Encoder base64Encoder = new BASE64Encoder();
filenameEncoder = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它瀏覽器
filenameEncoder = URLEncoder.encode(filename, "utf-8");
}
//獲取配置路徑
String url = FtpClientUtil.getStaticFile() + "/" + "目錄模板.xlsx";
//獲取文件流
InputStream in = new FileInputStream(url);
// 創建操作excel文件對象
XLSTransformer transformer = new XLSTransformer();
// 設置ContentType請求信息格式
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + filenameEncoder + ".xlsx");
// 要下載的這個文件的類型-----客戶端通過文件的MIME類型去區分類型
response.setContentType(request.getServletContext().getMimeType(filename));
ServletOutputStream outputStream = response.getOutputStream();
Map<String, Object> map = new HashMap<String, Object>();
map.put("list", list);
Workbook workbook = transformer.transformXLS(in, map);
workbook.write(outputStream);
workbook.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
msg = e.getMessage();
throw new BusinessException("導出失敗");
}
}
模板
前台vue代碼
Export() { let api ="" let a = document.createElement('a'); a.href = api; a.click(); },
