天天看點

Springboot中導入Excel

有時候我們需要導入Excel檔案,并讀取裡面的資料

在springboot中我們通常使用POI讀取解析Excel檔案

在使用POI之前我們需要引入必要的依賴

<!--POI,用于解析Excel檔案-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
           

準備好Excel源檔案

格式像這樣,标題無所謂

Paste_Image.png

Excel表的路徑可能有兩種,第一:本機路徑,第二:是個網絡路徑

我們先考慮第一種情況:本機路徑

将此檔案命名為:

測試.xlsx

,放到

resources

目錄下

下面做個通過導入exexl來實作使用者批量插入

對應的實體類

public class UserVo {
    String userId;
    String memberName;
    String password;
    String phoneNumber;
    String department;
    String grade;
省略set/get方法
}
           

然後具體的添加使用者的

dao

層和

service

層我就不具體寫了

controller層

public Object importExcel() throws Exception {
        XSSFWorkbook book = new XSSFWorkbook(new FileInputStream(ResourceUtils.getFile("classpath:測試.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", "導入成功");
        return jsonObject;
    }
           

要看清楚導入的Excel的字尾名,如果是

xls

,使用

HSSFWorkbook

;如果是

xlsx

XSSFWorkbook

,讀取兩種格式使用

Workbook

,不然會報異常

org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML.

相關方法說明

XSSFWorkbook book = new XSSFWorkbook()

得到Excel工作簿對象

XSSFSheet sheet = book.getSheetAt(0);

得到Excel工作表對象

sheet.getLastRowNum()

總行數

sheet.getRow()

得到Excel工作表的行

row.getCell()

得到Excel工作表指定行的單元格

在取資料的時候很容易碰到這樣的異常

Cannot get a text value from a numeric cell

無法将數值類型轉化成String

解決方法

①通過

String.valueOf()

方法轉

②将所有列中的内容都設定成String類型格式

row.getCell(要設定的列數,從0開始).setCellType(CellType.STRING);

Cell.CELL_TYPE_STRING已經替換為CellType.STRING,

官方不建議使用Cell.CELL_TYPE_STRING

第二:Excel檔案是個網絡路徑

FileInputStream

不支援從網絡路徑擷取資料

是以要使用

java.net

包下的URL

URL excelUrl = new URL(網絡位址);
XSSFWorkbook book = new XSSFWorkbook(excelUrl.openStream());
           
其中這裡有個問題要注意

如果你上傳的檔案的檔案名有中文,就會去中文進行轉義,通過urlencode(urlencode是一個函數,可将字元串以URL編碼,用于編碼處理。)

一般的url是不允許出現中文的

image.png

網絡路徑有中文,會報

java.io.FileNotFoundException

也就是找不到檔案,因為路徑有中文就找不到了,也許在浏覽器打開,但是在代碼中是找不到這個路徑的

之後的操作都一樣

參考

鐘述林

大牛的文章:

http://www.jianshu.com/p/cba49a1acc1d