用java确定微软Office的版本

sca*_*ity 4 java excel file-type version ms-office

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

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

有任何想法吗?

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

Rea*_*wTo 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
Run Code Online (Sandbox Code Playgroud)

这是一个简单的例子:

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();
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

您可能希望添加更多错误检查,并且从返回的路径中提取Office版本的解析将保留为练习;-)