java读取excel表格数据

柔光的暖阳◎ 2022-09-04 06:43 443阅读 0赞

1 背景介绍

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

2 导入依赖

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>3.16</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-ooxml</artifactId>
  9. <version>3.16</version>
  10. </dependency>

3 实现类

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

  1. public class ExceleToDbServiceImpl {
  2. public void parseExcelAppDataToDb() {
  3. // 得到APP表格中所有的数据
  4. String PATH = "xxx.xls"
  5. List<AppDO> listExcel = AppServiceImpl.getAllByExcel(PATH);
  6. LogUtil.info(LOGGER, listExcel.size());
  7. int sum = 0;
  8. for (IfrPlanAppDO ifrPlanAppDO : listExcel) {
  9. // 插入数据库逻辑 AppDAO实现了具体的插入功能
  10. // AppDAO.insert(ifrPlanAppDO);
  11. sum++;
  12. }
  13. }
  14. }

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

  1. public class PlanGetAppServiceImpl {
  2. //查询表格中所有的数据
  3. // AppDO为对应的POJO类,如Student类有name,age属性,每个属性有get和set方法
  4. public static List<AppDO> getAllByExcel(String file) {
  5. Workbook wb = null;
  6. Sheet sheet = null;
  7. Row row = null;
  8. List<AppDO> list = null;
  9. wb = readExcel(file);
  10. if (wb != null) {
  11. //用来存放表中数据
  12. list = new ArrayList<>();
  13. //获取第一个sheet
  14. sheet = wb.getSheetAt(0);
  15. //获取最大行数
  16. int rowNum = sheet.getPhysicalNumberOfRows();
  17. //获取第一行
  18. row = sheet.getRow(0);
  19. //获取最大列数
  20. // int colnum = row.getPhysicalNumberOfCells();
  21. for (int i = 1; i < rowNum; i++) {
  22. row = sheet.getRow(i);
  23. if (row != null) {
  24. // 读取表格中数据,第一列
  25. Cell cellAppName = row.getCell(0);
  26. String appName = cellAppName.getRichStringCellValue().getString();
  27. list.add(ifrPlanAppDO);
  28. } else {
  29. break;
  30. }
  31. }
  32. }
  33. return list;
  34. }
  35. }
  36. //读取excel
  37. public static Workbook readExcel(String filePath) {
  38. Workbook wb = null;
  39. if (filePath == null) {
  40. return null;
  41. }
  42. String extString = filePath.substring(filePath.indexOf('.'));
  43. InputStream is = null;
  44. try {
  45. is = new FileInputStream(filePath);
  46. if (".xls".equals(extString)) {
  47. return wb = new HSSFWorkbook(is);
  48. } else if (".xlsx".equals(extString)) {
  49. return wb = new XSSFWorkbook(is);
  50. } else {
  51. return wb = null;
  52. }
  53. } catch (FileNotFoundException e) {
  54. LOGGER.error(e.toString());
  55. } catch (IOException e) {
  56. LOGGER.error(e.toString());
  57. } catch (NoClassDefFoundError e) {
  58. LOGGER.error(e.toString());
  59. }
  60. return wb;
  61. }

发表评论

表情:
评论列表 (有 0 条评论,443人围观)

还没有评论,来说两句吧...

相关阅读