spring boot 使用 POI 读取Excel文件

内容简介

 本文主要介绍使用POI进行Excel文件的相关操作,涉及读取文件,获取sheet表格,对单元格内容进行读写操作,以及合并单元格的操作。

Excel文件目录

Excel模板文件存了resourse目录下,如下图:

POM引用

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>

重要说明

如果是xls格式,使用HSSFWorkbook,HSSFSheet,HSSFRow来进行相关操作
如果是xlsx格式,使用XSSFWorkbook,XSSFSheet,XSSFRow来进行相关操作

读取Excel文件

// 定义一个数据格式化对象
XSSFWorkbook wb = null;
try {
    //excel模板路径
    File cfgFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/ExcelTemplate/ContradictionMatrix.xlsx");
    InputStream in = new FileInputStream(cfgFile);
    //读取excel模板
    wb = new XSSFWorkbook(in);

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

获取sheet表格及读写单元格内容

//获取sheet表格,及读取单元格内容
XSSFSheet sheet = null;
try{
    sheet = wb.getSheetAt(0);
    //先将获取的单元格设置为String类型,下面使用getStringCellValue获取单元格内容
    //如果不设置为String类型,如果单元格是数字,则报如下异常
    //java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell
    sheet.getRow(2).getCell(2).setCellType(CellType.STRING);
    //读取单元格内容
    String cellValue = sheet.getRow(2).getCell(2).getStringCellValue();
    
    //添加一行
    XSSFRow row = sheet.createRow(1); //第2行开始写数据
    row.setHeight((short)400); //设置行高
    //向单元格写数据
    row.createCell(1).setCellValue("名称");
}
catch (Exception e){
    e.printStackTrace();
}

合并单元格

使用下面的语句合并单元格:

sheet.addMergedRegion(new CellRangeAddress(0,2,15,18));

看一下CellRangeAddress的构造函数:

/**
 * Creates new cell range. Indexes are zero-based.
 * 
 * @param firstRow Index of first row
 * @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow}
 * @param firstCol Index of first column
 * @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol}
 */
public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) {
    super(firstRow, lastRow, firstCol, lastCol);
    
    if (lastRow < firstRow || lastCol < firstCol)
        throw new IllegalArgumentException("lastRow < firstRow || lastCol < firstCol");
}

 

posted @ 2019-05-30 10:25  代码猫  阅读(11040)  评论(0编辑  收藏  举报