SpringBoot整合EsayPoi(Excel匯入匯出)
1.匯入jar包
<!--EasyPoi匯入匯出--> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>3.0.3</version> </dependency> <!-- 檔案上傳 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
2.匯入工具類(官網和百度都有)
package com.zzf.finals.utiles; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; public class ExcelUtiles { public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response){ ExportParams exportParams = new ExportParams(title, sheetName); exportParams.setCreateHeadRows(isCreateHeader); defaultExport(list, pojoClass, fileName, response, exportParams); } public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){ defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName)); } public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){ defaultExport(list, fileName, response); } private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) { Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list); if (workbook != null); downLoadExcel(fileName, response, workbook); } private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { //throw new NormalException(e.getMessage()); } } private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); if (workbook != null); downLoadExcel(fileName, response, workbook); } public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){ if (StringUtils.isBlank(filePath)){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); }catch (NoSuchElementException e){ //throw new NormalException("模板不能為空"); } catch (Exception e) { e.printStackTrace(); //throw new NormalException(e.getMessage()); } return list; } public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){ if (file == null){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); }catch (NoSuchElementException e){ // throw new NormalException("excel檔案不能為空"); } catch (Exception e) { //throw new NormalException(e.getMessage()); System.out.println(e.getMessage()); } return list; } }
3.編寫實體對映類
package com.zzf.finals.entity; import cn.afterturn.easypoi.excel.annotation.Excel; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "seckill") public class DemoExcel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Excel(name = "id" ,orderNum = "0") private Long seckillId; @Column(name = "name") @Excel(name = "姓名" ,orderNum = "1") private String name; @Column(name = "number") @Excel(name = "數量" ,orderNum = "2") private int number; @Column(name = "start_time") @Excel(name = "開始日期" ,orderNum = "3",importFormat = "yyyy-MM-dd HH:mm:ss")//exportFormat = "yyyy-MM-dd HH:mm:ss") private Date startTime; @Column(name = "end_time") @Excel(name = "結束日期" ,orderNum = "4",importFormat = "yyyy-MM-dd HH:mm:ss")//exportFormat = "yyyy-MM-dd HH:mm:ss") private Date endTime; @Column(name = "create_time") @Excel(name = "建立日期" ,orderNum = "5",importFormat = "yyyy-MM-dd HH:mm:ss")//exportFormat = "yyyy-MM-dd HH:mm:ss") private Date createTime; public Long getSeckillId() { return seckillId; } public void setSeckillId(Long seckillId) { this.seckillId = seckillId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "DemoExcel{" + "seckillId=" + seckillId + ", name='" + name + '\'' + ", number=" + number + ", startTime=" + startTime + ", endTime=" + endTime + ", createTime=" + createTime + '}'; } }
4.控制器程式碼
package com.zzf.finals.controller;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import com.zzf.finals.entity.DemoExcel;
import com.zzf.finals.repository.DemoExcelRepository;
import com.zzf.finals.service.DemoService;
import com.zzf.finals.utiles.ExcelUtiles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/Excel")
public class ExcelController {
@Autowired
private DemoExcelRepository demoExcelRepository;
@Autowired
private DemoService demoService;
@GetMapping("/export")
public void export(HttpServletResponse response) {
System.out.println(1);
// 模擬從資料庫獲取需要匯出的資料
List<DemoExcel> personList = demoExcelRepository.findAll();
// 匯出操作
ExcelUtiles.exportExcel(personList, "測試名", "什麼名字", DemoExcel.class, "測試.xls", response);
}
@PostMapping("/importExcel2")
public void importExcel2(@RequestParam("file") MultipartFile file) {
ImportParams importParams = new ImportParams();
// 資料處理
importParams.setHeadRows(1);
importParams.setTitleRows(1);
// 需要驗證
importParams.setNeedVerfiy(true);
try {
ExcelImportResult<DemoExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), DemoExcel.class,
importParams);
List<DemoExcel> successList = result.getList();
for (DemoExcel demoExcel : successList) {
System.out.println(demoExcel);
}
} catch (IOException e) {
} catch (Exception e) {
}
}
}
輸入連線後如圖所示。
匯入後如:
最最最簡單的匯入匯出就這麼完成了。
修改自定義樣式:
檢視原始碼我發現他內部封裝的是:
所以我們只需要設定這個樣式就行了如:
public class ShelterIExcelExportStyler extends ExcelExportStylerDefaultImpl implements IExcelExportStyler{
public ShelterIExcelExportStyler(Workbook workbook) {
super(workbook);
}
@Override
public CellStyle getTitleStyle(short color) {
CellStyle titleStyle = workbook.createCellStyle();
titleStyle.setAlignment(CellStyle.ALIGN_CENTER);
titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
titleStyle.setWrapText(true);
return titleStyle;
}
@Override
public CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {
CellStyle style = workbook.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setDataFormat(STRING_FORMAT);
if (isWarp) {
style.setWrapText(true);
}
return style;
}
@Override
public CellStyle getHeaderStyle(short color) {
CellStyle titleStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 20);
titleStyle.setFont(font);
titleStyle.setAlignment(CellStyle.ALIGN_CENTER);
titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
return titleStyle;
}
@Override
public CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
// font.setFontHeightInPoints((short) 15);
style.setFont(font);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setDataFormat(STRING_FORMAT);
if (isWarp) {
style.setWrapText(true);
}
return style;
}
}
這裡我只是簡單的修改了他預設字型大小。如果要設定表格的寬度不可以在這裡設定。
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName,
HttpServletResponse response, ExportParams exportParams, String sheetName) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
Sheet sheet=workbook.getSheet(sheetName);
// sheet.CreateRow(0).Height = (short)(200*20);
// sheet.createRow(0);
sheet.getRow(0).setHeight((short)(50*20));
sheet.getRow(1).setHeight((short)(30*20));
if (workbook != null); downLoadExcel(fileName, response, workbook);
}
他會呼叫ExportExcel返回一個Workbook物件,然後通過這個物件獲取Sheet才能改變行的寬度千萬不腰用CreateRow會覆蓋。
有些人會在使用匯入的時候出現只匯入一條資料或者列缺少的情況,個人推薦可以使用步進指令去除錯這段程式碼改成適用自己的”輪子“。我通過除錯發現儲存資料是這個方法:
private <T> List<T> importExcel(Collection<T> result, Sheet sheet, Class<?> pojoClass, ImportParams params,
Map<String, PictureData> pictures) throws Exception {
List collection = new ArrayList();
Map<String, ExcelImportEntity> excelParams = new HashMap<String, ExcelImportEntity>();
List<ExcelCollectionParams> excelCollection = new ArrayList<ExcelCollectionParams>();
String targetId = null;
if (!Map.class.equals(pojoClass)) {
Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);
ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class);
if (etarget != null) {
targetId = etarget.value();
}
getAllExcelField(targetId, fileds, excelParams, excelCollection, pojoClass, null, null);
}
Iterator<Row> rows = sheet.rowIterator();
for (int j = 0; j < params.getTitleRows(); j++) {
rows.next();
}
Map<Integer, String> titlemap = getTitleMap(rows, params, excelCollection);
checkIsValidTemplate(titlemap, excelParams, params, excelCollection);
Row row = null;
Object object = null;
String picId;
int readRow = 0;
// 跳過無效行
for (int i = 0; i < params.getStartRows(); i++) {
rows.next();
}
while (rows.hasNext()
&& (row == null || sheet.getLastRowNum() - row.getRowNum() > params.getLastOfInvalidRow())) {
if (params.getReadRows() > 0 && readRow > params.getReadRows()) {
break;
}
row = rows.next();
// Fix 如果row為無效行時候跳出
if (sheet.getLastRowNum() - row.getRowNum() < params.getLastOfInvalidRow()) {
break;
}
// 判斷是集合元素還是不是集合元素,如果是就繼續加入這個集合,不是就建立新的物件
// keyIndex 如果為空就不處理,仍然處理這一行
if (params.getKeyIndex() != null && !(row.getCell(params.getKeyIndex()) == null
|| StringUtils.isEmpty(getKeyValue(row.getCell(params.getKeyIndex())))) && object != null) {
for (ExcelCollectionParams param : excelCollection) {
addListContinue(object, param, row, titlemap, targetId, pictures, params);
}
} else {
object = PoiPublicUtil.createObject(pojoClass, targetId);
try {
// 標記為null的次數
int count = 0;
int sum = titlemap.size();
for (int i = row.getFirstCellNum(); i <= sum; i++) {
Cell cell = row.getCell(i);
boolean flag = true;
if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
count++;
flag = false;
}
String titleString = (String) titlemap.get(i);
if (excelParams.containsKey(titleString) || Map.class.equals(pojoClass)) {
if (excelParams.get(titleString) != null && excelParams.get(titleString).getType() == 2) {
picId = row.getRowNum() + "_" + i;
saveImage(object, picId, excelParams, titleString, pictures, params);
} else {
if (saveFieldValue(params, object, cell, excelParams, titleString, row)) {
if (flag)//只有當沒有count++過才能新增。
count++;
}
}
}
}
for (ExcelCollectionParams param : excelCollection) {
addListContinue(object, param, row, titlemap, targetId, pictures, params);
}
if (verifyingDataValidity(object, row, params, pojoClass)) {
// count等於0或者
if ((count == 0) || (count <= sum - 2))
collection.add(object);
} else {
// 如果為null的次數小於5則新增
// if (count!=0 || count < sum-3)
failCollection.add(object);
}
} catch (ExcelImportException e) {
LOGGER.error("excel import error , row num:{},obj:{}", readRow,
ReflectionToStringBuilder.toString(object));
if (!e.getType().equals(ExcelImportEnum.VERIFY_ERROR)) {
throw new ExcelImportException(e.getType(), e);
}
} catch (Exception e) {
LOGGER.error("excel import error , row num:{},obj:{}", readRow,
ReflectionToStringBuilder.toString(object));
throw new RuntimeException(e);
}
}
readRow++;
}
return collection;
}
這個類是
修改的位置在這裡,我通過修改這段程式碼使其強制進入else中可以拿到所有資料,然後判斷null的次數選擇是否新增。
適用自己的輪子才是最好的輪子……
文件地址:http://easypoi.mydoc.io/
參考:https://www.jianshu.com/p/5d67fb720ece
相關推薦
SpringBoot整合EsayPoi(Excel匯入匯出)
1.匯入jar包 <!--EasyPoi匯入匯出--> <dependency> <groupId>cn.afterturn</groupId> <
SpringBoot整合POI實現檔案匯出Excel,匯入Excel更新Mysql資料庫資料
上傳功能 轉載自https://blog.csdn.net/xyy1028/article/details/79054749原創寫的非常好,但是每個人都有自己的業務邏輯;所以在研究了一點之後,打上註釋,方便新手理解,同時也方便自己記憶;專案目錄applicat
springboot2整合easypoi,實現Excel匯入匯出
1.新增Maven依賴 <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <v
SpringBoot中使用POI,快速實現Excel匯入匯出
匯出Excel 整體來說,Excel有.xls和.xlsx,那麼在POI中這兩個也對應兩個不同的類,但是類名不同,方法基本都是一致的,因此我這裡將只介紹.xls一種。 整體來說,可以分為如下七個步驟: 1.建立Excel文件 H
SSM框架整合(基本CRUD+分頁+Excel匯入匯出)
前言 之前學習了SSM(Spring+SpringMVC+Mybatis),一直想自己弄一個小專案自己來寫一下,最近寫了一個,該專案使用Maven進行依賴包管理,使用MySQL5.6資料庫實現了一個管理系統的基礎功能。 (如果喜歡,可以點一個Star又不
JAVA:Excel匯入匯出詳解(3)--匯出
Excel匯出 一、設定查詢條件 注意:無法通過Ajax下載 jsp程式碼 <form class="col-sm-2" action="/manage/order/download" method="post" onsubmit="checkForm()"
JAVA:Excel匯入匯出詳解(2)--匯入
1. 瀏覽資料夾,選擇需要上傳的檔案 程式碼 jsp <li class="col-sm-1"> <span>上 &a
TP5操作Excel匯入匯出資料庫
匯入: <?phpnamespace app\index\controller;use think\Controller;use think\Db;use think\Loader;class Upload extends Controller{ public function upload()
開發指南專題十五 JEECG微雲快速開發平臺EXCEL匯入匯出
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!  
原始碼的excel匯入匯出
獲取所有資料,將資料進行有序切割,在進行遍歷,將其匯出。 //設定header header("content-type:text/html;charset=utf-8"); //連線資料庫 $link=mysqli_connec
POI-Excel匯入匯出 詳細實現程式碼
1.介面效果: 1)點選批量匯入,彈出檔案選擇框,選擇檔案,點選開啟,檔案開始上傳。 &nb
Vue中excel匯入匯出
npm安裝 npm install -S file-saver xlsx(這裡其實安裝了2個依賴) npm install -D script-loader 在src下建立一個資料夾,包含兩個檔案: Blob.js,Export2Excel.js下載地址:https://gitee
Spring使用POI實現Excel匯入匯出
Apache POI 是建立和維護操作各種符合Office Open XML(OOXML)標準和微軟的OLE 2複合文件格式(OLE2)的Java API。用它可以使用Java讀取和建立,修改MS Excel檔案.而且,還可以使用Java讀取和建立MS Word和MSPowerPoint檔案。Ap
excel匯入 匯出
PHP頁面 //設定header header("content-Type:text/html;charset=utf-8"); //設定檔案大小的限制 ini_set("memory_limit",'1024M'); //引入類檔案 Loa
Java POI大資料量的Excel匯入匯出
1. 大資料量的匯入 當Excel中的資料量超過10萬行時,在用POI讀取檔案流時很容易引起失敗,需要引入xlsx-streamer來進行資源的開啟,剩下的處理同POI處理上百行資料量類似:filePath=>FileInputStream=>Workboo
Java通過Poi的開發Excel匯入匯出和下載功能
原文連結:http://www.zjhuiwan.cn/toDetail?articleId=1812131133133410000 最近有用到Excel的下載、匯入、匯出功能。提供一個Excel模板給使用者下載,使用者根據規範填寫模板然後再匯入Excel資料,儲存到資料庫,也可匯出類表資料
jFinal中excel匯入匯出
jFinal中excel匯入匯出 Jfinal剛接觸不久,之前接觸的java框架基本上是jeesite,所以,當接到excel匯入及模板下載任務時,第一個想到的還是jeesite對Apache POI 3.9的簡單封裝,實現Excel的匯入匯出功能(只適用於簡單的匯入匯出,不合適複雜的表格或使
easypoi Excel匯入匯出 (工具類)
1.用到的jar 紅色的必須的。 下面那些是執行起來,缺哪個就導哪個。 如果報錯提示沒有這個方法的話,重啟Tomcat,還不好使就是jar包版本不對,找個高點的版本。 easypoi-annotation-3.1.0.jar easypoi-base-3.1.0.j
關於excel_io.jar excel匯入匯出工具的使用說明
目錄 excel_io.jar 工具是依賴於poi和poi-ooxml兩個apached的jar包 進行的開發的,分別依賴3.14 和3.17兩個版本,請下載的使用者注意如果名字為excel_io-poi3.14.jar na依賴的就
Jboot框架excel匯入匯出模板下載的簡單封裝
需要用到的的類 主控制器 package io.jboot.admin.controller.ImportController; import java.util.ArrayList; import java.util.List; import javax.val