有時(shí)候我們需要導(dǎo)入Excel文件汇跨,并讀取里面的數(shù)據(jù)
在SpringBoot中我們通常使用POI讀取解析Excel文件
在使用POI之前我們需要引入必要的依賴(lài)
<!--POI,用于解析Excel文件-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
準(zhǔn)備好Excel源文件
格式像這樣,標(biāo)題無(wú)所謂
Excel表的路徑可能有兩種,第一:本機(jī)路徑公条,第二:是個(gè)網(wǎng)絡(luò)路徑
我們先考慮第一種情況:本機(jī)路徑
將此文件命名為:ceshi.xlsx
垃它,放到resources
目錄下纽谒,盡量改為英文名做院,中文可能會(huì)報(bào)錯(cuò)
下面做個(gè)通過(guò)導(dǎo)入exexl來(lái)實(shí)現(xiàn)用戶(hù)批量插入
對(duì)應(yīng)的實(shí)體類(lèi)
public class UserVo {
String userId;
String memberName;
String password;
String phoneNumber;
String department;
String grade;
省略set/get方法
}
然后具體的添加用戶(hù)的dao
層和service
層我就不具體寫(xiě)了
controller層
public Object importExcel() throws Exception {
XSSFWorkbook book = new XSSFWorkbook(new FileInputStream(ResourceUtils.getFile("classpath:ceshi.xlsx")));
XSSFSheet sheet = book.getSheetAt(0);
UserVo userVo = new UserVo();
for (int i = 2; i < sheet.getLastRowNum() + 1; i++) {
XSSFRow row = sheet.getRow(i);
userVo.setMemberName(row.getCell(0).getStringCellValue());
userVo.setPhoneNumber(String.valueOf((long) row.getCell(1).getNumericCellValue()));
userVo.setPassword(row.getCell(2).getStringCellValue());
userVo.setDepartment(row.getCell(3).getStringCellValue());
userVo.setGrade(String.valueOf((long) row.getCell(4).getNumericCellValue()));
userService.addUser(userVo);
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "導(dǎo)入成功");
return jsonObject;
}
要看清楚導(dǎo)入的Excel的后綴名沉填,
如果是xls
市框,使用HSSFWorkbook
霞扬;
如果是xlsx
,使用XSSFWorkbook
,
讀取兩種格式使用Workbook
,不然會(huì)報(bào)異常org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML.
相關(guān)方法說(shuō)明
XSSFWorkbook book = new XSSFWorkbook()
得到Excel工作簿對(duì)象
XSSFSheet sheet = book.getSheetAt(0);
得到Excel工作表對(duì)象
sheet.getLastRowNum()
總行數(shù)
sheet.getRow()
得到Excel工作表的行
row.getCell()
得到Excel工作表指定行的單元格
在取數(shù)據(jù)的時(shí)候很容易碰到這樣的異常Cannot get a text value from a numeric cell
無(wú)法將數(shù)值類(lèi)型轉(zhuǎn)化成String
解決方法
①通過(guò)String.valueOf()方法轉(zhuǎn)
②將所有列中的內(nèi)容都設(shè)置成String類(lèi)型格式
row.getCell(要設(shè)置的列數(shù)祥得,從0開(kāi)始).setCellType(CellType.STRING);
Cell.CELL_TYPE_STRING
已經(jīng)替換為CellType.STRING
,
官方不建議使用Cell.CELL_TYPE_STRING
第二:Excel文件是個(gè)網(wǎng)絡(luò)路徑
FileInputStream
不支持從網(wǎng)絡(luò)路徑獲取數(shù)據(jù)
所以要使用java.net
包下的URL
URL excelUrl = new URL(網(wǎng)絡(luò)地址);
XSSFWorkbook book = new XSSFWorkbook(excelUrl.openStream());
其中這里有個(gè)問(wèn)題要注意
如果你上傳的文件的文件名有中文兔沃,就會(huì)去中文進(jìn)行轉(zhuǎn)義,通過(guò)urlencode(urlencode是一個(gè)函數(shù)级及,可將字符串以URL編碼乒疏,用于編碼處理。)
一般的url是不允許出現(xiàn)中文的
網(wǎng)絡(luò)路徑有中文饮焦,會(huì)報(bào)
java.io.FileNotFoundException
也就是找不到文件怕吴,因?yàn)槁窂接兄形木驼也坏搅耍苍S在瀏覽器打開(kāi)县踢,但是在代碼中是找不到這個(gè)路徑的之后的操作都一樣