用java确定微软Office的版本

时间:2011-05-31 21:51:43

标签: java excel ms-office version file-type

我写了一个程序,它创建了一组输出到excel电子表格的数据。我最初使用jexcel库将数据写入文件,但我想更新程序,以便它可以检查并查看是否应创建“.xls”或“.xlsx”文件,然后写入适当的文件类型。 Apache POI似乎是写入“.xlsx”文件的最佳选择,但是有关确定正确文件类型的任何想法?

我可以让用户在命名文件时选择,但这对用户来说似乎是额外的工作,我假设有些用户不知道他们想要什么文件类型。

有什么想法吗?

另外,我假设操作系统是Windows,用户有一些excel版本,在其他情况下我只选择默认文件类型。

4 个答案:

答案 0 :(得分:6)

一种方法是调用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 :(得分:1)

您可以在注册表中搜索密钥:

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

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

read/write to Windows Registry using Java

答案 2 :(得分:0)

如果您愿意深入注册表(例如jregistrykey),this PowerShell script的翻译版本应该按照您的意愿进行。

答案 3 :(得分:0)

看看OfficeVer

您可以将其实现到脚本中或用于代码分析。它像Java一样是跨平台的,因此编译并直接实现它不是什么大问题。 它通过提取.docx和xlsx文件,然后读取版本以及直接从.doc和.xls文件读取来工作。 OfficeVer还扩展了对.pdf文件的支持(撰写本文时,当前版本为1.03.1)

相关问题