DateUtil.isCellDateFormatted(Cell cell)在java p o i中不起作用

时间:2017-08-15 10:58:18

标签: java apache-poi

enter image description here

这是我在A4单元格中输入的日期。我怎样才能在我的java程序中得到它。我的DateUtil.isCellDateFormated(Cell)不起作用。 我使用过DataFormatter它没有给我任何日子。 enter image description here

PUGIXML_WCHAR_MODE

1 个答案:

答案 0 :(得分:0)

您似乎可以尝试使用Cell.html#getDateCellValue()方法。

一些简单的例子:

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

public class ExternalCaller {

    public static final String MM_DD_YYYY = "MM/dd/yyyy";

    public static void main(String... args) throws IOException {
        FileInputStream file = new FileInputStream(new File("D:\\test.xls"));
        HSSFWorkbook workbook = new HSSFWorkbook(file);
        HSSFSheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                int cellType = cell.getCellType();
                try {
                    determineValue(cellType, cell);
                } catch (UnsupportedOperationException ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }
    }

    public static void determineValue(int cellType, Cell cell) {
        switch (cellType) {
            case Cell.CELL_TYPE_NUMERIC:
                determineDate(cell);
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.println(cell.getStringCellValue());
                break;
            default:
                throw new UnsupportedOperationException("This type of cell should be additionally implemented");
        }
    }

    private static void determineDate(Cell cell) {
        short dataFormat = cell.getCellStyle().getDataFormat();

        if (14 == dataFormat) {
            Date dateCellValue = cell.getDateCellValue();
            System.out.println(new SimpleDateFormat(MM_DD_YYYY).format(dateCellValue));
        } else {
            System.out.println(new DataFormatter().formatCellValue(cell));
        }
    }
}

单元格的输出

enter image description here

将是:

123.0546
Killme
78%
11/22/1995
This type of cell should be additionally implemented
1190

如果它适合您,请告诉我,否则我会删除答案。