1 背景介绍

java读取excel文件有很多的应用场景,如读取数据后入库,或者做数据分析,预处理等等,那么如何做到读取文件呢,下面看具体步骤。
笔者使用环境是IDEA2020.1,jdk8.

2 导入依赖

	<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>

3 实现类

ExceleToDbServiceImpl类:负责获取数据后,使用DAO层接口插入到数据库表中。

public class ExceleToDbServiceImpl {
    public void parseExcelAppDataToDb() {
        // 得到APP表格中所有的数据
        String PATH  = "xxx.xls"
        List<AppDO> listExcel = AppServiceImpl.getAllByExcel(PATH);

        LogUtil.info(LOGGER, listExcel.size());
        int sum = 0;
        for (IfrPlanAppDO ifrPlanAppDO : listExcel) {
            // 插入数据库逻辑 AppDAO实现了具体的插入功能
            // AppDAO.insert(ifrPlanAppDO);
            sum++;
        }
        
    }
}

AppServiceImpl类: 获取数据的具体逻辑实现

public class PlanGetAppServiceImpl {
    //查询表格中所有的数据
  
   // AppDO为对应的POJO类,如Student类有name,age属性,每个属性有get和set方法
    public static List<AppDO> getAllByExcel(String file) {
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<AppDO> list = null;
        wb = readExcel(file);
        if (wb != null) {
            //用来存放表中数据
            list = new ArrayList<>();
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数
            int rowNum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
//            int colnum = row.getPhysicalNumberOfCells();
            for (int i = 1; i < rowNum; i++) {
                row = sheet.getRow(i);
                if (row != null) {
                     // 读取表格中数据,第一列
                    Cell cellAppName = row.getCell(0);
                    String appName = cellAppName.getRichStringCellValue().getString();  
                    list.add(ifrPlanAppDO);
                } else {
                    break;
                }
            }
        }
        return list;
    }
}



  //读取excel
    public static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.indexOf('.'));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }

        } catch (FileNotFoundException e) {
            LOGGER.error(e.toString());
        } catch (IOException e) {
            LOGGER.error(e.toString());
        } catch (NoClassDefFoundError e) {
            LOGGER.error(e.toString());
        }
        return wb;
    }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐