2013-03-13 21 views
2

我目前使用POI來讀取excel文件,它工作得很好,除非它不能讀取舊格式(BIFF5/office 95)的xls文件來解決這個問題,我正在捕捉OldExcelFormatException,並且在這種情況下調用一個將讀取使用jxl的xls文件。我想要實現的是編寫相同的代碼,但沒有捕獲異常。這裏是當前的工作代碼:如何增強這個使用POI和JXL讀取xls文件的java類?

public void translate() throws IOException, CmpException 
{ 
    ArrayList<String> row = null; 

    try 
    { 
    // create a new org.apache.poi.poifs.filesystem.Filesystem 
    POIFSFileSystem poifs = new POIFSFileSystem(fin); 
    w = new HSSFWorkbook(poifs); 
    } 
    catch (OldExcelFormatException e) // OldExcelFormatException 
    { 
    w = null; 
    System.out.println("OldExcelFormatException"); 
    translateBIFF5(); 
    } 
    catch (Exception e) // Any Exception 
    { 
    w = null; 
    } 

    if (w != null) 
    { 
    // read the excel file using POI 
    } 
} 

private void translateBIFF5() throws IOException, CmpException 
{ 
    ArrayList<String> row = null; 
    try 
    { 
    jxl_w = Workbook.getWorkbook(excelFile); 
    } 
    catch (Exception e) // Any Exception 
    { 
    jxl_w = null; 
    } 

    if (jxl_w != null) 
    { 
    // read the excel file using jxl 
    } 
} 

回答

0

沒關係傢伙。我自己找到了解決方案。訣竅是查看工作簿名稱:對於excel 95/97,工作簿名稱爲「Book」,而對於新格式,工作簿名稱爲「WorkBook」。所以這裏是我一直在尋找的編碼:

POIFSFileSystem poifs = new POIFSFileSystem(fin); 

    DirectoryNode directory = poifs.getRoot(); 
    Iterator<Entry> i  = directory.getEntries(); 
    while (i.hasNext()) 
    { 
    Entry e   = i.next(); 
    String bookName = e.getName(); 
    if (bookName.equals("Book")) 
    { 
     System.out.println("This is an old format"); 
    } 
    else 
    { 
     System.out.println("This is a new format"); 
    } 
    } 
+0

實際上這個代碼仍然有一個錯誤,因爲我迭代條目,我將無法將它們轉換爲Excel我不得不重新迭代以某種方式在他們身上 – Wael 2013-03-13 14:54:19

相關問題