如何知道在Java中的Excel文件版本?

我想读取java中的excel文件。 我有一些旧格式的Excel文件(Excel 95)和其他新格式(Excel 2007)。 我目前正在使用poi,但它不能读取旧格式的excel文件。 所以我需要的是一个传递文件名的函数,如果格式为旧格式(BIFF5),将返回值为true的布尔值,如果格式为新(BIFF8),则返回false。 这个function的需要是允许我使用旧版本的jxl和新版本的poi。

这里是我有的代码:

try { // create a new org.apache.poi.poifs.filesystem.Filesystem POIFSFileSystem poifs = new POIFSFileSystem(fin); w = new HSSFWorkbook(poifs); } catch (IOException e) { w = null; throw e; } catch (OutOfMemoryError e) // java.lang.OutOfMemoryError: { w = null; throw e; } catch (OldExcelFormatException e) // OldExcelFormatException { w = null; System.out.println("OldExcelFormatException"); translateBIFF5(); } private void translateBIFF5() throws IOException, CmpException { ArrayList<String> row = null; try { jxl_w = Workbook.getWorkbook(excelFile); } catch (BiffException e) { jxl_w = null; e.printStackTrace(); } catch (IOException e) { jxl_w = null; throw e; } catch (OutOfMemoryError e) // java.lang.OutOfMemoryError: { jxl_w = null; throw e; } if (jxl_w != null) { try { for (currentSheet = 0; currentSheet < jxl_w.getNumberOfSheets(); currentSheet++) { jxl_sheet = jxl_w.getSheet(currentSheet); . . . . . 

我build议尝试Andy Khan的JExcel而不是POI。 我不认为POI是特别好devise或logging。 我已经与JExcel很好运了。 尝试一下。

一种方法是调用Windows ASSOC和FTYPE命令,捕获输出并parsing它以确定安装的Office版本。

 C:\Users\me>assoc .xls .xls=Excel.Sheet.8 C:\Users\me>ftype Excel.sheet.8 Excel.sheet.8="C:\Program Files (x86)\Microsoft Office\Office12\EXCEL.EXE" /e 

这里有个简单的例子:

 import java.io.*; public class ShowOfficeInstalled { public static void main(String argv[]) { try { Process p = Runtime.getRuntime().exec (new String [] { "cmd.exe", "/c", "assoc", ".xls"}); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); String extensionType = input.readLine(); input.close(); // extract type if (extensionType == null) { System.out.println("no office installed ?"); System.exit(1); } String fileType[] = extensionType.split("="); p = Runtime.getRuntime().exec (new String [] { "cmd.exe", "/c", "ftype", fileType[1]}); input = new BufferedReader (new InputStreamReader(p.getInputStream())); String fileAssociation = input.readLine(); // extract path String officePath = fileAssociation.split("=")[1]; System.out.println(officePath); } catch (Exception err) { err.printStackTrace(); } } } 

要么

您可以在registry中search关键字:

HKEY_LOCAL_MACHINE \ Software \ Microsoft \ Windows \ CurrentVersion \ App Paths

这可能需要一些工作,正如这个问题所certificate的那样:

使用Java读/写Windowsregistry