1.引入依賴
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.5</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.5</version></dependency><!--<!– Poi-tl Word 模板引擎–>--><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.12.2</version></dependency>
2.示例代碼
public download(String id, HttpServletResponse response){File file = null;
try{Item item = itemService.fetchById(id);
InputStream in = new ClassPathResource("/template/item.xlsx").getInputStream();
File temp = File.createTempFile("temp","xlsx");
OutputStream out = new FileOutputStream(temp);
IOUtils.copy(in,out);//apache poi
out.flush();
out.close();
in.close();//基于臨時文件通過輸入流生成xlsx對象并寫入數據
XSSFWorkbook workbook = new XSSFWorkbook(temp);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.createRow(2);
row.createCell(0).setCellValue(item.getStudentId());
row.createCell(1).setCellValue(item.getName());
row.createCell(2).setCellValue(item.getSex());//輸出流生成導出的文件
String fileName = String.format("學生信息下載%s.xlsx",DateUtil.format(DateUtil.date(),"yyyyMMddHHmmss"));
//DateUtil 引用的是hutool
file = new File(fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
workbook.write(fileOutputStream);
fileOutputStream.flush():
fileOutputStream.close();
//把文件寫到response的輸出流中 最后再刪除兩個中間文件
response.reset();
response.setContentType("application/vnd.ms-excel; charset=utf-8");
// 解決下載的excel報錯問題
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition",String.format("attachment; filename=%s",URLEncoder.encode(fileName, StandardCharsets.UTF_8.displayName())));exportFile(response, new FileInputStream(file));}catch(Exception e){throw new RuntimeException(e.getMessage());
}finally {if(null != file) file.delete();}return "ok";}public static void exportFile(HttpServletResponse response, InputStream is){byte[] buff = new byte[1024];BufferedInputStream bis = null;OutputStream os = null;
try{
os = response.getOutputStream();
bis = new BufferedInputStream(is);
int i = bis.read(buff);
while(i!=-1){os.write(buff, 0, buff.length);os.flush();i = bis.read(buff);}}catch (IOException e){e.printStackTrace();
}finally {if(null != bis){try{bis.close();}catch (IOException e){e.printStackTrace();
}}if( os != null){try{os.close();}catch (IOException e ){e.printStackTrace();
}}}}
前端接收時,需要用blob進行接收
即將response.type = "blob"
示例代碼
download().done(res=>{const url = URL.createObjcetURL(res);//創建一個指向Blob的URLconst a = document.createElement("a");//創建一個a標簽用于下載a.href = url;
let fileName = `學生信息${new Date().format("yyyyMMddhhmmssSSS")}.xlsx`;
a.download = fileName; // 設置下載文件名
document.body.appendChild(a);//將a標簽添加到文檔中以觸發下載
a.click();//模擬點擊下載文件
document.body.removeChild(a);//移除a標簽})