用Java确定Microsoft Office的版本

问题描述

|| 我编写了一个程序,该程序创建了一组输出到excel电子表格的数据。我最初使用jexcel库将数据写入文件,但是我想更新程序,以便它可以检查并查看是否应创建\“。xls \”或\“。xlsx \”文件,然后写入适当的文档类型。就写入\ .xlsx \文件而言,Apache POI似乎是最佳选择,但是有关确定正确文件类型的任何想法吗? 我可以在命名文件时让用户选择,但这似乎对用户来说是额外的工作,我假设有些用户不知道他们想要的文件类型。 有任何想法吗? 另外,我假设操作系统是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\",\"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版本的解析作为练习;-)     ,        您可以在注册表中搜索密钥: HKEY_LOCAL_MACHINE \\ Software \\ Microsoft \\ Windows \\ CurrentVersion \\ App路径 如以下问题所示,这可能需要做一些工作: 使用Java读取/写入Windows注册表     ,        如果您愿意进入注册表(例如使用jregistrykey),则可以执行此PowerShell脚本的翻译版本。     ,        看看OfficeVer。 您可以将其实现到脚本中或用于代码分析。它就像Java一样是跨平台的,因此编译并直接实现它不是什么大问题。 它通过提取.docx和xlsx文件,然后读取版本以及直接从.doc和.xls文件读取来工作。 OfficeVer还扩展了对.pdf文件的支持(撰写本文时的当前版本为1.03.1)