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 like to update the program so that it can check and see whether is should create a ".xls" or ".xlsx" file, then write to the appropriate document type. Apache POI seems to be the best option in terms of writing to a ".xlsx" file, but any ideas about determining the correct file type?
I could just have the user choose when naming the file, but that seems like extra work for the user and I'm assuming that there are users who don't know what file type they'd want.
Any ideas?
Also, I'm assuming the OS is windows and the user has some version of excel, in other cases I'll just choose a default file type.
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 ;-)
You can search in the registry for the key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths
This will probably require some work, as evidenced by this question:
read/write to Windows Registry using Java
If you're willing to dive into the registry (eg with jregistrykey) a translated version of this PowerShell script should do what you want.
Take a look at OfficeVer.
You can implement it to your script or use it for code analysis. It's cross-platform much like Java, so compiling it and implementing it directly shouldn't be a big deal.
It works by extracting .docx and xlsx files and then reading the version, as well as reading directly from .doc and .xls files.
OfficeVer as well has extended their support to .pdf files (current version as of time of writing is 1.03.1)