Java uses POI to process Excel's time format

problem:

Use Java's POI to process time cells in Excel, often the format we get is not what we want. For example:
Excel
After setting up as shown in the figure above, pass the following code

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

The output obtained is

29-一月-2021

Solution:

Through Cellthe getNumericCellValue()method of the class and the method of the HSSFDateUtilclass getJavaDate, the complete code is as follows:

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();
        }
    }
}

The output of the above code is:

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

Welcome to follow my WeChat public account:
WeChat public account

Guess you like

Origin blog.csdn.net/michael_f2008/article/details/113382800