numéro6 numéro6 - 4 months ago 25
Java Question

How can I convert a .ods file to an .xls file

I need to convert a OpenDocument spreadsheet (

.ods
) to an Excel compatible-file (
.xls
or
.xlsx
)

I know it's possible using
libreoffice
cli
. I would like to do this exact thing using Java. I know that Java could run the command-line process but I would prefer a JVM-only solution (not requiring libreoffice on the environment). Is there any open-source library that could help?

Answer

I ended up by calling libreoffice.

File outputDirectory = source.getParentFile();
String[] command = {
        "/usr/bin/libreoffice",
        "--headless",
        "--invisible",
        "-env:UserInstallation=file://" + SystemUtils.getJavaIoTmpDir().getAbsolutePath(), // prevent conversion to fail or just do nothing if libreoffice is already running
        "--convert-to",
        "ods",
        "--outdir",
        outputDirectory,
        source.getAbsolutePath()
};
try {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.directory(outputDirectory);
    Process process = processBuilder.start();
    int returnValue = process.waitFor();
    if (returnValue == 0) {
        log.debug("process ended successfully");
    } else {
        log.error("process ended with error code " + returnValue);
    }
} catch (IOException e) {
    throw new UncheckedIOException("cannot convert " + source, e);
}
Comments