本章讲解如何使用poi对excel文件的读取和写入
1、在pox.xml文件中导入依赖:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
如果去maven仓库搜索,请看一下选择
2、获取指定单元格
FileInputStream fis = new FileInputStream("src\\main\\resources\\test.xlsx"); //获取Workbook对象 Workbook workbook = WorkbookFactory.create(fis); //获取Sheet对象,getSheetAt(索引):是根据索引获取sheet,getSheet("sheet名称"):根据sheet名称获取sheeet Sheet sheetAt = workbook.getSheetAt(0); //获取行对象 Row row = sheetAt.getRow(1); //获取单元格对象 Cell cell = row.getCell(1); //把单元格的类型转换为String的,不然是其他类型的获取会报错 cell.setCellType(CellType.STRING); String stringCellValue = cell.getStringCellValue();
fis.close();
3、循环取全部的
FileInputStream fis = new FileInputStream("src\\main\\resources\\test.xlsx"); //获取Workbook对象 Workbook workbook = WorkbookFactory.create(fis); //获取Sheet对象,getSheetAt(索引):是根据索引获取sheet,getSheet("sheet名称"):根据sheet名称获取sheeet Sheet sheetAt = workbook.getSheetAt(0); //获取最后一行的下标 int lastRowNum = sheetAt.getLastRowNum(); for (int i = 0; i < lastRowNum; i++){ Row row = sheetAt.getRow(i); //获取当前行的最后一个单元格的下标 short lastCellNum = row.getLastCellNum(); for (int j = 0; j < lastCellNum; j++){ Cell cell = row.getCell(j); cell.setCellType(CellType.STRING); String stringCellValue = cell.getStringCellValue(); System.out.println(stringCellValue); } }
fis.close();
4、对指定单元格的内容进行修改后回写到本文件,也可以存草其他文件。如果文件不存在则创建,如果文件存在则先清空数据
FileInputStream fis = new FileInputStream("src\\main\\resources\\test.xlsx"); //获取Workbook对象 Workbook workbook = WorkbookFactory.create(fis); //先把资源关闭,不然会一直占用资源, fis.close(); //获取Sheet对象,getSheetAt(索引):是根据索引获取sheet,getSheet("sheet名称"):根据sheet名称获取sheeet Sheet sheetAt = workbook.getSheetAt(0); Row row = sheetAt.getRow(1); Cell cell = row.getCell(1); //对单元格进行判断,如果单元格的内容为空会报空指针异常 if (cell == null){ cell = row.createCell(1); cell.setCellValue("test"); }else { cell.setCellValue("test"); } FileOutputStream fos = new FileOutputStream("src\\main\\resources\\test.xlsx"); workbook.write(fos); fos.close(); }