2013-03-13 65 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