java获取xlsx文件中日期格式化
时间: 2024-05-10 12:18:30 浏览: 100
在Java中,可以使用Apache POI库来读取、写入和操作Excel文件。对于日期格式化,可以使用Java中的SimpleDateFormat类来实现。
以下是一个示例代码,演示如何从xlsx文件中读取日期并将其格式化为指定的字符串格式:
```java
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDateFormatter {
public static void main(String[] args) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
File file = new File("test.xlsx");
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
Cell cell = workbook.getSheetAt(0).getRow(0).getCell(0);
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(sdf.format(cell.getDateCellValue()));
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们使用SimpleDateFormat类来指定日期格式。然后,我们打开Excel文件并获取其中的单元格。如果单元格包含日期值,则我们使用DateUtil类来检查它是否为日期格式。如果是,我们将其格式化为指定的字符串格式并打印出来。最后,我们关闭工作簿。
需要注意的是,由于XSSF模式支持的日期范围比HSSF模式更广,因此我们在本例中使用XSSFWorkbook类来读取xlsx文件。如果您正在使用xls文件,则应使用HSSFWorkbook类。
阅读全文
相关推荐


















