1、安装引用Apache POI
Maven中pom.xml添加如下:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
2、读取Excel中时间日期数据
InputStream inputStream = new FileInputStream("D://test.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(inputStream); Sheet sheet = wb.getSheetAt(0); Cell cell = sheet.getRow(0).getCell(0);// 获取第一行第一列的单元格 if (cell != null) { if (cell.getCellTypeEnum() != CellType.STRING && HSSFDateUtil.isCellDateFormatted(cell)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue()); String value = sdf.format(date); System.out.println(value); } } wb.close();
3、读取Excel中其它数据
//1.使用流读取文件 FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\KingHao\\Desktop\\poiTest.xlsx")); //2.使用 xssf 创建 workbook XSSFWorkbook excel = new XSSFWorkbook(fileInputStream); //3.根据索引获取sheet XSSFSheet sheet = excel.getSheetAt(0); //4.遍历row for (Row row:sheet){ System.out.println(row); for (Cell cell:row){ switch (cell.getCellType()){ //判断读取的数据中是否有String类型的 case Cell.CELL_TYPE_STRING: System.out.println(cell.getStringCellValue()); break; case Cell.CELL_TYPE_NUMERIC: /* 判断是否读取到了日期数据: 如果是那就进行格式转换,否则会读取的科学计数值 不是就输出number 数字 */ if (HSSFDateUtil.isCellDateFormatted(cell)){ Date date = cell.getDateCellValue(); //格式转换 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String format = sdf.format(date); System.out.println(format); }else { System.out.println(cell.getNumericCellValue()); } break; } } } excel.close();
或者
switch(cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "\t\t"); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); System.out.print(dateFormat.format(cell.getDateCellValue()) + "\t\t"); } else { System.out.print(cell.getNumericCellValue() + "\t\t"); } break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t\t"); break; }
相关文档:
Java 使用POI填充Word表格内容和复制模板行属性方法示例代码