Java code to print spreadsheet rows to the console

Shared Libraries
Forum rules
For sharing working examples of macros / scripts. These can be in any script language supported by OpenOffice.org [Basic, Python, Netbean] or as source code files in Java or C# even - but requires the actual source code listing. This section is not for asking questions about writing your own macros.
Post Reply
Yu0JbXks
Posts: 1
Joined: Sun Dec 11, 2011 3:59 am

Java code to print spreadsheet rows to the console

Post by Yu0JbXks »

Sharing some simple code that takes an ODS/Scalc spreadsheet (potentially password protected) and prints all the rows. I use this to then grep for certain things that I commonly need to look up:

Code: Select all

import java.io.File;

import ooo.connector.BootstrapSocketConnector;

import com.sun.star.beans.PropertyValue;
import com.sun.star.container.XIndexAccess;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;                                                                                                                                 
import com.sun.star.sheet.XCellRangeAddressable;                                                                                                                                 
import com.sun.star.sheet.XSheetCellCursor;                                                                                                                                      
import com.sun.star.sheet.XSpreadsheet;                                                                                                                                          
import com.sun.star.sheet.XSpreadsheetDocument;                                                                                                                                  
import com.sun.star.sheet.XSpreadsheets;                                                                                                                                         
import com.sun.star.sheet.XUsedAreaCursor;                                                                                                                                       
import com.sun.star.table.XCell;                                                                                                                                                 
import com.sun.star.uno.UnoRuntime;

/**
 * <code>
 * http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/FirstSteps/Configuration
 * file:///opt/libreoffice/basis3.3/sdk/docs/java/ref/index.html
 * http://user.services.openoffice.org/en/forum/viewtopic.php?f=45&t=1844
 * </code>
 * 
 */
public class readods {
        public static void main(String... args) {
                try {
                        if (args == null || args.length == 0) {
                                throw new Exception("No file name specified");
                        }
                        int i = 0;
                        String password = null;
                        int sheetIndex = 0;
                        int maxCols = -1;
                        String programDir = "/opt/libreoffice/program";
                        String find0 = null;
                        String find1 = null;
                        boolean verbose = false;
                        for (; i < args.length - 1; i++) {
                                if (args[i].equals("-password")) {
                                        if (i == args.length - 2) {
                                                System.out.print("Password: ");
                                                password = new String(System.console().readPassword());
                                        } else {
                                                password = args[++i];
                                        }
                                } else if (args[i].equals("-sheet")) {
                                        sheetIndex = Integer.parseInt(args[++i]);
                                } else if (args[i].equals("-programdir")) {
                                        programDir = args[++i];
                                } else if (args[i].equals("-find0")) {
                                        find0 = args[++i];
                                } else if (args[i].equals("-find1")) {
                                        find1 = args[++i];
                                } else if (args[i].equals("-verbose")) {
                                        verbose = true;
                                } else if (args[i].equals("-maxcols")) {
                                        maxCols = Integer.parseInt(args[++i]);
                                }
                        }
                        String file = args[i];
                        if (!new File(file).exists()) {
                                throw new Exception("File does not exist");
                        }
                        if (verbose) {
                                System.out.println("Reading " + file);
                        }
                        String sUrl = file;
                        if (sUrl.indexOf("private:") != 0) {
                                java.io.File sourceFile = new java.io.File(file);
                                StringBuffer sbTmp = new StringBuffer("file:///");
                                sbTmp.append(sourceFile.getCanonicalPath().replace('\\', '/'));
                                sUrl = sbTmp.toString();
                        }

                        com.sun.star.uno.XComponentContext xContext = null;
                        // get the remote office component context
                        // xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
                        // http://user.services.openoffice.org/en/forum/viewtopic.php?f=44&t=2520
                        xContext = BootstrapSocketConnector.bootstrap(programDir);
                        if (verbose) {
                                System.out.println("Initialized");
                        }

                        XMultiComponentFactory xMCF = null;
                        XComponentLoader xCLoader;
                        XSpreadsheetDocument myDoc = null;
                        XComponent xComp = null;

                        xMCF = xContext.getServiceManager();

                        // create a new instance of the the desktop
                        Object oDesktop = xMCF.createInstanceWithContext(
                                        "com.sun.star.frame.Desktop", xContext);

                        // query the desktop object for the XComponentLoader
                        xCLoader = (XComponentLoader) UnoRuntime.queryInterface(
                                        XComponentLoader.class, oDesktop);

                        int length = 1;
                        if (password != null) {
                                length++;
                        }
                        PropertyValue[] props = new PropertyValue[length];
                        props[0] = new PropertyValue();
                        props[0].Name = "Hidden";
                        props[0].Value = new Boolean(true);
                        if (password != null) {
                                props[1] = new PropertyValue();
                                props[1].Name = "Password";
                                props[1].Value = password;
                        }

                        xComp = xCLoader.loadComponentFromURL(sUrl, "_blank", 0, props);
                        myDoc = (XSpreadsheetDocument) UnoRuntime.queryInterface(
                                        XSpreadsheetDocument.class, xComp);
                        if (myDoc != null) {

                                XSpreadsheets xSheets = myDoc.getSheets();
                                XIndexAccess oIndexSheets = (XIndexAccess) UnoRuntime
                                                .queryInterface(XIndexAccess.class, xSheets);
                                XSpreadsheet xSheet = (XSpreadsheet) UnoRuntime
                                                .queryInterface(XSpreadsheet.class,
                                                                oIndexSheets.getByIndex(sheetIndex));
                                XSheetCellCursor cursor = xSheet.createCursor();
                                XUsedAreaCursor xUsedAreaCursor = UnoRuntime.queryInterface(
                                                XUsedAreaCursor.class, cursor);

                                xUsedAreaCursor.gotoEndOfUsedArea(true);
                                XCellRangeAddressable xCellRangeAddressable = UnoRuntime
                                                .queryInterface(XCellRangeAddressable.class,
                                                                xUsedAreaCursor);
                                int rowCount = xCellRangeAddressable.getRangeAddress().EndRow;
                                int colCount = xCellRangeAddressable.getRangeAddress().EndColumn;
                                if (maxCols != -1 && colCount > maxCols) {
                                        colCount = maxCols;
                                }
                                for (int r = 0; r <= rowCount; r++) {
                                        if (find0 != null) {
                                                if (!xSheet.getCellByPosition(0, r).getFormula()
                                                                .contains(find0)) {
                                                        continue;
                                                }
                                        }
                                        if (find1 != null) {
                                                if (!xSheet.getCellByPosition(1, r).getFormula()
                                                                .contains(find1)) {
                                                        continue;
                                                }
                                        }
                                        for (int c = 0; c <= colCount; c++) {
                                                XCell cell = xSheet.getCellByPosition(c, r);
                                                String val = cell.getFormula();
                                                if (c > 0) {
                                                        System.out.print(',');
                                                }
                                                // XText text = (XText)
                                                // UnoRuntime.queryInterface(XText.class, cell);
                                                System.out.print(val);
                                        }
                                        System.out.println();
                                }
                                // XCell cell = xSheet.getCellByPosition(0, 0);
                                // System.out.println(cell.getFormula());
                        } else {
                                throw new Exception(
                                                "Could not load document. If password protected, pass -password STR");
                        }
                        xComp.dispose();
                        System.exit(0);
                } catch (Throwable t) {
                        t.printStackTrace();
                }
        }
}
Run with:

Code: Select all

#!/bin/sh
java -cp $(dirname $0)/:/opt/libreoffice/ure/share/java/juh.jar:/opt/libreoffice/ure/share/java/jurt.jar:/opt/libreoffice/ure/share/java/ridl.jar:/opt/libreoffice/basis3.3/program/classes/unoil.jar:$(dirname $0)/bootstrapconnector.jar readods -sheet 1 -maxcols 5 $* -password myfile.ods
Post Reply