javascript
easypoi导出数值型_SpringBoot使用EasyPoi进行数据导入导出Excel(一)
在實際項目開發中,對于Excel的導入導出還是很常見的需求,比如說將數據根據模板批量導入到數據庫中,以及將數據庫中的數據批量導出陳Excel的形式
現有需求:
下載固定的導入Excel模板
導入Excel中的數據進數據庫
將數據進行Ecel導出
本篇文章,先總結excel靜態模板文件的下載
一. 準備工作
準備靜態文件
導入 EasyPOI 的依賴
1.7.9
4.1.0
cn.afterturn
easypoi-spring-boot-starter
${easypoi.version}
cn.afterturn
easypoi-base
${easypoi.version}
cn.afterturn
easypoi-web
${easypoi.version}
cn.afterturn
easypoi-annotation
${easypoi.version}
二. 使用easypoi進行靜態模板的導出
excel靜態模板下載,有兩種方式:
第一種,在http頭中指定輸出文件流的類型為"application/vnd.ms-excel"類型時,輸出流時就不需要添加輸出文件的后綴名;
@GetMapping("/templateDownload")
public ResponseEntity templateDownload(@PathVariable("organizationId")Long tenantId,
HttpServletResponse response ) {
try {
// 獲取資源中的模板文件
ClassPathResource resource = new ClassPathResource("static\\拉線-設備主數據導入模板.xlsx");
InputStream inputStream = resource.getInputStream();
Workbook wb = WorkbookFactory.create(inputStream);
String fileName="拉線-設備主數據導入模板";
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
wb.write(response.getOutputStream());
return Results.success();
}catch (IOException e){
return Results.error(e.getMessage());
}
第二種,指定文件流的類型為"multipart/form-data"時,輸出流時需要判斷文件是.xls/.xlsx,并且加上后綴名。
@GetMapping("/templateDownload1")
public ResponseEntity templateDownload1(@PathVariable("organizationId")Long tenantId,
HttpServletResponse response ) {
try {
// 獲取資源中的模板文件
ClassPathResource resource = new ClassPathResource("static\\拉線-設備主數據導入模板.xlsx");
InputStream inputStream = resource.getInputStream();
// 根據不同excel創建不同對象,Excel2003版本-->HSSFWorkbook,Excel2007版本-->XSSFWorkbook
Workbook wb = WorkbookFactory.create(inputStream);
response.reset();
response.setContentType("multipart/form-data");
String fileName="拉線-設備主數據導入模板";
// 判斷excel文件類型,下載獲取到的模板并重新命名
System.out.println(wb.getClass().getSimpleName());
if (wb.getClass().getSimpleName().equals("HSSFWorkbook")) {
response.setHeader("Content-Disposition",
"attachment; filename=" + "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
} else {
response.setHeader("Content-Disposition",
"attachment; filename=" + "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
}
wb.write(response.getOutputStream());
return Results.success();
}catch (IOException e){
return Results.error(e.getMessage());
}
這部分我只是大概寫了一下測試實現,在實際的工作中,導入導出等代碼肯定是有特別高的復用率的,可以將代碼中其中一部分抽離出來一個公用的工具類進行調用
總結
以上是生活随笔為你收集整理的easypoi导出数值型_SpringBoot使用EasyPoi进行数据导入导出Excel(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 建立索引和主外约束_Mysql索引原理
- 下一篇: activemenu怎么拼 vue_Vu