excel数据的导出

该博客介绍了如何在Java中使用Apache POI库来读取Excel文件数据。首先,引入了必要的依赖,然后提供了读取Excel文件的代码实现,包括对xlsx和xls两种格式的支持,以及从指定工作表中提取Role对象的详细步骤。
摘要由CSDN通过智能技术生成

一、需求

读取Excel表格数据

二、添加依赖

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

三、具体实现

 @Override
    public List<Role> readExcelData(String excelPath,String sheetName) throws Exception {
        log.info("开始读取位置{}为的Excel文件,工作簿名称为{}",excelPath,sheetName);
        InputStream io = new FileInputStream(excelPath);
        Workbook workbook ;
        if(StringUtils.endsWith(excelPath,"xlsx")){
            workbook = new XSSFWorkbook(io);
        }else if(StringUtils.endsWith(excelPath,"xls")){
            workbook = new HSSFWorkbook(io);
        }else {
            throw new MissingResourceException("选择的文件后缀只支持xls、xlsx两种格式",ExcelServiceImpl.class.getName(),"excelPath");
        }
        if(org.springframework.util.StringUtils.isEmpty(workbook)){
            throw new Exception("excel文件不存在");
        }
        List<Role> roleList = new ArrayList<>();
        Sheet sheet = workbook.getSheet(sheetName);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int k = 1; k < sheet.getLastRowNum()+1; k++) {
            Row row = sheet.getRow(k);
            Role role = Role.builder().roleName(row.getCell(0).getStringCellValue())
                    .description(row.getCell(1).getStringCellValue())
                    .createTime(sdf.format(row.getCell(2).getDateCellValue()))
                    .updateTime(sdf.format(row.getCell(3).getDateCellValue())).build();
            roleList.add(role);
        }
        return roleList;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值