JAVA-POI-读取excel文件

雨点打透心脏的1/2处 2022-05-16 09:45 450阅读 0赞

使用Apache POI读取excel文件,兼容.xlsx和.xls
POM

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

ExcelTest

  1. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  2. import org.apache.poi.ss.usermodel.*;
  3. import java.io.File;
  4. import java.io.IOException;
  5. /** * @author wzx * @time 2018/8/19 */
  6. public class ExcelTest {
  7. public static final String SAMPLE_XLSX_FILE_PATH = "D:\\test1.xlsx";
  8. public static final String SAMPLE_XLSX_FILE_PATH2 = "D:\\test2.xls";
  9. public static void main(String[] args) throws IOException, InvalidFormatException {
  10. readExcel();
  11. }
  12. public static void readExcel() throws IOException, InvalidFormatException {
  13. Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH2));
  14. System.out.println("sheets" + workbook.getNumberOfSheets());
  15. //获取第一张表
  16. Sheet sheet = workbook.getSheetAt(0);
  17. for (Row row : sheet) {
  18. int index = 0;
  19. for (Cell cell : row) {
  20. //读取数据前设置单元格类型
  21. // cell.setCellType(CellType.STRING);
  22. // String value = cell.getStringCellValue();
  23. // System.out.print("value:" + value + " ");
  24. if(index == 0) {
  25. //先设置单元格类型,再读取数据
  26. cell.setCellType(CellType.STRING);
  27. String value = cell.getStringCellValue();
  28. System.out.print("value:" + value + " ");
  29. }
  30. if(index == 1) {
  31. //先设置单元格类型,再读取数据
  32. cell.setCellType(CellType.NUMERIC);
  33. Double value = cell.getNumericCellValue();
  34. System.out.print("value:" + value + " ");
  35. }
  36. index++;
  37. }
  38. System.out.println();
  39. }
  40. }
  41. }

发表评论

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

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

相关阅读