Springboot读取excel

Posted 诺浅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot读取excel相关的知识,希望对你有一定的参考价值。

1. 导包

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

读取方法:

File file = new File("/Users/zhongguangxi/Documents/yrt-file/kcsj.xlsx");
InputStream is = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(is);
// 如果excel的后缀是xls,说明是03版,需要用如下方法
// Workbook workbook = new HSSFWorkbook(is);
//读取工作簿的第一张表格
Sheet sheet = workbook.getSheetAt(0);
for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) 
	Row row = sheet.getRow(i);
	// 读取单元格内容
	getCellValue(row.getCell(1))

getCellValue方法:

private static String getCellValue(Cell cell) 

    if (cell == null) 
        return "";
    

    if ("NUMERIC".equals(cell.getCellType().name())) 
        return new BigDecimal(cell.getNumericCellValue()).toString();
     else if ("STRING".equals(cell.getCellType().name()))
        return StringUtils.trimToEmpty(cell.getStringCellValue());
    else if ("FORMULA".equals(cell.getCellType().name())) 
        return StringUtils.trimToEmpty(cell.getCellFormula());
     else if ("BLANK".equals(cell.getCellType().name())) 
        return "";
     else if ("BOOLEAN".equals(cell.getCellType().name())) 
        return String.valueOf(cell.getBooleanCellValue());
     else if ("ERROR".equals(cell.getCellType().name())) 
        return "ERROR";
     else 
        return cell.toString().trim();
    

如果excel中的时间类型会报错,无法用getCellValue方法,需要特殊处理一下

Cell cell1 = row.getCell(13);
if (cell1 != null) 
    if (cell1.getDateCellValue()!=null) 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String value = sdf.format(cell1.getDateCellValue());
        hmi.setOverdueDate(StringUtils.isEmpty(value) ? null : LocalDate.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    

以上是关于Springboot读取excel的主要内容,如果未能解决你的问题,请参考以下文章

Springboot读取excel

springboot 实现excel文件上传

SpringBoot基于EasyExcel解析Excel实现文件导出导入读取写入

java在线读取Excel内容

springboot结合POI导入导出excel文件

SpringBoot系列之对Excel报表的校验提示