Java使用POI從Excel讀取數(shù)據(jù)并存入數(shù)據(jù)庫(解決讀取到空行問題)
項目場景:
需要從Excel讀取多行數(shù)據(jù),映射到j(luò)ava對象,并存入到數(shù)據(jù)庫當(dāng)中(單Sheet版)
問題分析
例如:讀取數(shù)據(jù)映射到j(luò)ava實體類的時候,發(fā)現(xiàn)了有一條數(shù)據(jù)的屬性都為null,導(dǎo)致一些方法的空指針異常。通過debug我們發(fā)現(xiàn),實際上Excel當(dāng)中數(shù)據(jù)有4條(包括header),但是在使用poi讀取并映射到j(luò)ava實體類的時候卻映射了5條。

解決方案:
既然最后一條數(shù)據(jù)讀到的是沒有數(shù)據(jù)的一行,我們就可以在遍歷excel數(shù)據(jù)的時候加一條判斷,每一行當(dāng)中每一個單元格的通過poi讀取后,在java中崗位cell類型的對象,只需判斷是否為null,若為null直接結(jié)束遍歷即可。

其中最外層循環(huán),為遍歷每行數(shù)據(jù)。內(nèi)層循環(huán)為遍歷每行數(shù)據(jù)當(dāng)中的單元格Cell,內(nèi)層循環(huán)的數(shù)量是根據(jù)第一行(header頭部標題)的數(shù)量來決定的。
完整代碼:
maven先導(dǎo)入poi相關(guān)jar包,本人使用的是 4.1.2 版本。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>該代碼為單sheet版本,若為多sheet版本只需在外層加一層for循環(huán)遍歷sheet即可。
若Excel表中數(shù)據(jù)為日期,可以使用cell.getDateCellValue()來獲取,cell提供的方法很多,可以根據(jù)具體情況來進行獲取。
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springblade.busi.entity.PersonalInfo;
import org.springblade.busi.framework.annotation.InfoChangeAnnotation;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ExcelToObject1 {
/**
* 讀取Excel文件,版本:只讀取基本信息一個Sheet,若有需要多個sheet在增加for循環(huán)
*
* @param file
* @return
*/
public List<PersonalInfo> toPersonalInfo(MultipartFile file) {
//創(chuàng)建返回對象
List<PersonalInfo> persons = new ArrayList<>();
try (InputStream fis = file.getInputStream();
Workbook workbook = new XSSFWorkbook(fis)) {
Class<?> clazz = PersonalInfo.class;
//只讀取基本信息一個Sheet
Sheet sheet = workbook.getSheetAt(0);
Row headerRow = sheet.getRow(0);
List<String> columnNames = new ArrayList<>();
Iterator<Cell> cellIterator = headerRow.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
columnNames.add(cell.getStringCellValue());
}
for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row row = sheet.getRow(rowIndex);
PersonalInfo person = (PersonalInfo) clazz.newInstance();
//獲取Excel當(dāng)前行的第一位,若未null則不處理 ---> 防止poi讀取Excel多讀取沒有數(shù)據(jù)的一行,導(dǎo)致非空字段為空。
Cell cellNow = row.getCell(0);
if (cellNow == null) {
break;
}
for (int columnIndex = 0; columnIndex < columnNames.size(); columnIndex++) {
Cell cell = row.getCell(columnIndex);
String columnName = columnNames.get(columnIndex);
//通過實體類注解與Excel頭部中文進行映射
Field field = getFieldByColumnName(clazz, columnName);
if (field != null) {
field.setAccessible(true);
field.set(person, getCellValueAsString(cell));
}
}
//處理每一行Excel加到返回對象當(dāng)中
persons.add(person);
}
} catch (IOException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return persons;
}
//通過實體類注解與Excel頭部中文進行映射
private static Field getFieldByColumnName(Class<?> clazz, String columnName) {
for (Field field : clazz.getDeclaredFields()) {
InfoChangeAnnotation annotation = field.getAnnotation(InfoChangeAnnotation.class);
if (annotation != null && annotation.value().equals(columnName)) {
return field;
}
}
return null;
}
//獲取每個單元格數(shù)據(jù)并轉(zhuǎn)為String,其他類型在上方做了ifelse
private static String getCellValueAsString(Cell cell) {
if (cell == null) {
return null;
}
cell.setCellType(CellType.STRING);
String cellValue = cell.getStringCellValue();
System.out.println("getCellValueAsString:" + cellValue);
return cellValue;
}在映射java實體類的時候需要在其實體類屬性添加注解,注解可以自行創(chuàng)建,也可以引用其他帶有value的注解,本文章使用的是 @InfoChangeAnnotation("Excel表中第一行的中文")。直接可以與Excel表頭進行映射。 上述代碼中PersonalInfo為需要映射到j(luò)ava的實體類,必須根據(jù)實際情況進行修改。
@InfoChangeAnnotation("姓名")
private String personalName;總結(jié)
到此這篇關(guān)于Java使用POI從Excel讀取數(shù)據(jù)并存入數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)Java讀取Excel數(shù)據(jù)存入數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot+MyBatis實現(xiàn)登錄案例
前端時間在網(wǎng)上看到有朋友在學(xué)習(xí)springboot項目的搭建過程,今天就抽空給大家分享一個案例幫助大家學(xué)習(xí)SpringBoot+MyBatis實現(xiàn)登錄功能,具體實現(xiàn)代碼跟隨小編一起看看吧2021-06-06
Idea連接數(shù)據(jù)庫并執(zhí)行SQL語句的方法示例
這篇文章主要介紹了Idea連接數(shù)據(jù)庫并執(zhí)行SQL語句的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Java集合排序規(guī)則接口Comparator用法解析
這篇文章主要介紹了Java集合排序規(guī)則接口Comparator用法解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
springmvc的validator數(shù)據(jù)校驗的實現(xiàn)示例代碼
這篇文章主要介紹了springmvc的數(shù)據(jù)校驗的實現(xiàn)示例代碼, 具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
idea創(chuàng)建SpringBoot項目時Type選maven?project和maven?pom有何區(qū)別
Maven是一個Java工程的管理工具,跟其相同功能的工具如Gradle,下面這篇文章主要給大家介紹了關(guān)于idea創(chuàng)建SpringBoot項目時Type選maven?project和maven?pom有何區(qū)別的相關(guān)資料,需要的朋友可以參考下2023-02-02
SpringBoot Session共享實現(xiàn)圖解
這篇文章主要介紹了SpringBoot Session共享實現(xiàn)圖解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-01-01
ByteArrayOutputStream與InputStream互相轉(zhuǎn)換方式
這篇文章主要介紹了ByteArrayOutputStream與InputStream互相轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12

