使用java确定Microsoft Office的版本
我编写了一个程序,用于创建一组输出到Excel电子表格的数据。我最初使用jexcel库将数据写入文件,但我想更新程序,以便它可以检查并确定是否应该创建“.xls”或“.xlsx”文件,然后写入适当的文件类型。在写入“.xlsx”文件方面,Apache POI似乎是最佳选择,但是有关确定正确文件类型的任何想法?使用java确定Microsoft Office的版本
我可以让用户在命名文件时选择,但这似乎是额外的工作,我假设有用户不知道他们想要什么文件类型。
任何想法?
此外,我假设操作系统是Windows和用户有一些版本的Excel,在其他情况下,我只会选择一个默认的文件类型。
一种方法是调用Windows ASSOC和FTYPE命令,捕获输出并解析它以确定安装的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();
}
}
}
您可能需要增加更多的错误检查和解析,以提取返回的路径Office版本留作练习;-)
+1学到了新东西。之前不知道ftype和assoc命令。 – mikek3332002 2011-06-01 03:06:46
可以在注册表中的键搜索:
HKEY_LOCAL_MACHINE \ SOFTWARE \微软\的Windows \ CurrentVersion \ App路径
这可能需要一些工作,就证明了这样一个问题:
Excel可以读取这两种类型。为什么不继续你在做什么? – EJP 2011-06-01 01:06:49