java poi 读取excel日期格式的数据
时间: 2023-09-24 09:14:01 浏览: 79
你可以使用Java的POI库来读取Excel日期格式的数据。具体步骤如下:
1. 使用POI库中的Workbook类打开Excel文件。
2. 确定要读取的工作表。
3. 遍历工作表的每一行,读取日期格式的单元格。
4. 使用Java中的日期格式化函数将日期数据转换为标准日期格式。
以下是示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcelDate {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("your_file.xls"));
//Create Workbook instance holding reference to .xlsx file
Workbook workbook = WorkbookFactory.create(file);
//Get first/desired sheet from the workbook
Sheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
for (Row row : sheet) {
//Iterate through each cell one by one
for (Cell cell : row) {
//Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.print(cell.getDateCellValue() + "\t");
} else {
System.out.print(cell.getNumericCellValue() + "\t");
}
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该代码将遍历Excel中的每一个单元格,检查其类型并格式化日期数据。