2017-12-08 33 views
0

schoolproject에 대한 testdate를 열어야합니다. 이 테스트 날짜는 숫자, 문자, 날짜 및 시간을 포함하는 Excel (xlsx) 파일입니다. 하지만 아래의 코드는 Excel 파일을 읽지 만 42538.01.153481443E9과 같은 이상한 숫자가 표시됩니다. 이후. 소수가 후 엑셀Apoche POI를 사용하여 java에서 excel (xlsx) 파일 읽기 (이상한 숫자 얻기)

public class Page4_Controller implements Initializable { 

    @FXML 
    private Button button1; 

    public void Button1Action(ActionEvent event) throws IOException { 
     //Initialize excel file 
     FileChooser fc = new FileChooser(); 
     fc.getExtensionFilters().addAll(
       new ExtensionFilter("Excel Files", "*.xlsx")); 
     File selectedFile = fc.showOpenDialog(null); 

     // Read file 
     readXLSXFile(selectedFile.getAbsolutePath()); 
    } 

    public static void readXLSXFile(String excelFilePath) throws IOException { 
     FileInputStream fys = new FileInputStream(new File(excelFilePath)); 

     //Create workbook instance that refers to .xlsx file 
     XSSFWorkbook wb = new XSSFWorkbook(fys); 

     //Create a sheet object to retrive the sheet 
     XSSFSheet sheet = wb.getSheetAt(0); 

     //That is for evalueate the cell type 
     FormulaEvaluator forlulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); 
     DataFormatter df = new DataFormatter(); 

     //Default data for database (comes later) 
     //String airport = sheet.getRow(1).getCell(1).getStringCellValue(); 
     //Date date = sheet.getRow(2).getCell(1).getDateCellValue(); 

     for (Row row : sheet) { 
      for (Cell cell : row) { 
       switch (forlulaEvaluator.evaluateInCell(cell).getCellType()) { 
        //If cell is a numeric format 
        case Cell.CELL_TYPE_NUMERIC: 
         System.out.print(cell.getNumericCellValue() + "\t"); 
         System.out.print(df.formatCellValue(cell) + "\t"); 
         break; 
        //If cell is a string format 
        case Cell.CELL_TYPE_STRING: 
         System.out.print(cell.getRichStringCellValue() + "\t"); 
         break; 
       } 

      } 
      System.out.println(); 
     } 
    } 

    @Override 
    public void initialize(URL location, ResourceBundle resources) { 
    } 

} 
+1

42538.0은 날짜 (2016-06-17 00:00) 일 수 있습니다. 세포 유형이 DATE인지 확인해야합니다. – Stefan

+0

날짜는 다음과 같이 작성됩니다. Date Found : 17-Jun-2016이며 셀 유형은 date입니다. –

답변

0

날짜 소수 구분 앞의 부분이 일 이후 1900년 1월 1일되는 「시리얼 번호」및 일부로 표현되는 하루 중 일부이므로 정오가 0.5입니다. 따라서 숫자 자체를 얻으려면 수동으로 변환해야합니다.

POI는 전환을 수행 할 수 있습니다. 예를 들어 How to read Excel cell having Date with Apache POI?을 참조하십시오.

+0

영어가 너무 좋지 않아서 프로그래밍에 익숙하지 않습니다. 코드에서 변경하고 게시 할 수 있습니까? 정말 감사하겠습니다 :) –

+1

Nope. 게시 한 링크에는이를 수행하는 좋은 예가 있습니다. 편집 : 코드 형식이 여기에 없습니다. 링크 된 게시물의 답변을 확인하십시오. – SurfMan

+0

게시 한 링크는 내 코드와 아무 관련이 없습니다. 특정 행에 대해서는 sais이지만 원하는 것은 아닙니다 ..... –

0

이것은 내가 자바에서 읽을 필요 엑셀 파일 enter image description here

2

날짜를 두 번 값과 String으로 셀의 형식의 값을 반환 DataFormatter.formatCellValue (전지 셀)로 Excel에서 내부적으로 저장됩니다 세포 유형에 관계없이. 따라서 df.formatCellValue (cell)을 호출하면 셀의 double 값을 문자열로 반환합니다.

switch (cell.getCellType()) { 
    // ... 
    case CellType.NUMERIC: 
     // Check if a cell contains a date. Since dates are stored internally in Excel as double values we infer it is a date if it is formatted as such. 
     if (DateUtil.isCellDateFormatted(cell)) { 
      // Get the value of the cell as a date. Returns a java.util.Date. 
      System.out.println(cell.getDateCellValue()); 
     } else { 
      System.out.println(cell.getNumericCellValue()); 
     } 
    // ... 
} 

출처 :

편집

에만 시간을 포함

엑셀 세포는 자신의 날짜 부분은 당신은 셀 시간 또는 날짜인지 확인하기 위해이 정보를 사용할 수 있습니다 12월 31일 1899에 고정이 : 추출 년, 그것은 1899의 경우 그것은 시간 세포입니다.

SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); 
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); 
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); 

switch (cell.getCellType()) { 

    case CellType.NUMERIC: 
    if (DateUtil.isCellDateFormatted(cell)) { 
     Date dateCellValue = cell.getDateCellValue(); 
     String year = yearFormat.format(dateCellValue); 
     if (year.equals("1899")) 
      System.out.println(timeFormat.format(dateCellValue)); 
     else 
      System.out.println(dateFormat.format(dateCellValue)); 
    } else { 
     System.out.println(cell.getNumericCellValue()); 
    } 

} 
+0

날짜 : 10 월 9 일 토요일 00:00:00 CEST 2016, 날짜 : 10-sep-2016 \t하지만 내가 얻는 것은 Date : 42623.0입니다. \t 10-sep-2016 위의 코드를 참조하십시오. –

+0

그 다음에 올바른 날짜를 얻고 있습니다. 원하는대로 형식을 지정하면됩니다. SimpleDateFormat을 사용할 수 있습니다. sdf = new SimpleDateFormat ("dd-MM-yyyy"); System.out.println (sdf.format (cell.getDateCellValue())); – Luke

+0

고맙습니다. 읽으려는 것처럼 날짜를 읽었지만, 이제는 날짜처럼 19:25의 TIME을 읽습니다. 그래서 그것은 19:25가되어야하지만 그것은 1899 년 31 월 12 일입니다. –