determine version of microsoft office with java

后端 未结 4 2148
灰色年华
灰色年华 2021-01-06 03:42

I wrote a program that creates a set of data that is outputted to an excel spreadsheet. I was originally using the jexcel library to write the data to the file, but I\'d lik

4条回答
  •  失恋的感觉
    2021-01-06 04:31

    One way is to call the Windows ASSOC and FTYPE commands, capture the output and parse it to determine the Office version installed.

    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
    

    Here a quick example :

    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();
          }
        }
      }
    

    You may want to add more error checking and the parsing to extract the Office version from the returned path is left as an exercise ;-)

提交回复
热议问题