天天看点

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