Java 利用POI处理Excel的时间格式

问题:

用Java的POI处理Excel中的时间单元格,往往得到的格式不是我们想要的。比如:
Excel
按上图中方式设置好后,通过以下代码

 XSSFRow row = sheet.getRow(0);
 Cell cell = row.getCell(0);
 System.out.println(cell);

得到的输出是

29-一月-2021

解决办法:

通过Cell类的getNumericCellValue()方法和HSSFDateUtil类的getJavaDate方法进行处理,完整代码如下:

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetExcelDate {
    
    
    public static void main(String[] args) {
    
    
        String excel_file_path = "D:\\时间.xlsx";
        String sheet_name = "Sheet1";

        try {
    
    
            //读取Excel文件
            FileInputStream fileInputStream = new FileInputStream(excel_file_path);
            XSSFWorkbook sheets = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = sheets.getSheet(sheet_name);

            //获取第0行第0列的单元格
            XSSFRow row = sheet.getRow(0);
            Cell cell = row.getCell(0);
            System.out.println(cell);

            //CST格式
            double val = cell.getNumericCellValue();
            Date date = HSSFDateUtil.getJavaDate(val);
            System.out.println(date);

            //Unix时间戳
            long time = date.getTime();
            System.out.println(time);

            //自定义格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(time);
            System.out.println(format);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

以上代码的输出为:

29-一月-2021
Fri Jan 29 08:45:47 CST 2021
1611881147000
2021-01-29 08:45:47

欢迎关注我的微信公众号:
微信公众号

猜你喜欢

转载自blog.csdn.net/michael_f2008/article/details/113382800