Search in sources :

Example 1 with ComIApplication

use of com.sun.jna.platform.win32.COM.util.office.word.ComIApplication in project jna by java-native-access.

the class Excelautomation_KB_219151_Mod method main.

public static void main(String[] args) throws IOException {
    // Initialize COM Subsystem
    Ole32.INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_MULTITHREADED);
    // Initialize Factory for COM object creation
    Factory fact = new Factory();
    // Set LCID for calls to english locale. Without this formulas need
    // to be specified in the users locale.
    fact.setLCID(new LCID(0x0409));
    try {
        // Start excel application
        ComExcel_Application excel = fact.createObject(ComExcel_Application.class);
        ComIApplication excelApp = excel.queryInterface(ComIApplication.class);
        // Set visiblite of application
        excelApp.setVisible(true);
        Helper.sleep(5);
        // Get a new workbook.
        ComIWorkbook wb = excelApp.getWorkbooks().Add();
        ComIWorksheet sheet = wb.getActiveSheet();
        // Add table headers going cell by cell.
        sheet.getCells().getItem(1, 1).setValue("First Name");
        sheet.getCells().getItem(1, 2).setValue("Last Name");
        sheet.getCells().getItem(1, 3).setValue("Full Name");
        sheet.getCells().getItem(1, 4).setValue("Salary");
        // Create an array to set multiple values at once.
        SAFEARRAY saNames = safeVariantArrayFromJava(new String[][] { { "John", "Smith" }, { "Tom", "Brown" }, { "Sue", "Thomas" }, { "Jane", "Jones" }, { "Adam", "Johnson" } });
        // Fill A2:B6 with an array of values (First and Last Names).
        VARIANT valueHolder = new VARIANT();
        valueHolder.setValue(Variant.VT_ARRAY | Variant.VT_VARIANT, saNames);
        sheet.getRange("A2", "B6").setValue(valueHolder);
        saNames.destroy();
        // Fill C2:C6 with a relative formula (=A2 & " " & B2).
        sheet.getRange("C2", "C6").setFormula("= A2 & \" \" & B2");
        // Fill D2:D6 with a formula(=RAND()*100000) and apply format.
        sheet.getRange("D2", "D6").setFormula("=RAND()*100000");
        sheet.getRange("D2", "D6").setNumberFormat("$0.00");
        // AutoFit columns A:D.
        sheet.getRange("A1", "D2").getEntireColumn().AutoFit();
        displayQuaterlySales(sheet);
        File tempFile = Helper.createNotExistingFile("exceloutput", ".xlsx");
        System.out.println("Writing output to: " + tempFile.getAbsolutePath());
        wb.SaveAs(tempFile.getAbsolutePath());
        excelApp.setUserControl(true);
    } finally {
        fact.disposeAll();
        Ole32.INSTANCE.CoUninitialize();
    }
    System.exit(0);
}
Also used : LCID(com.sun.jna.platform.win32.WinDef.LCID) SAFEARRAY(com.sun.jna.platform.win32.OaIdl.SAFEARRAY) ComIWorkbook(com.sun.jna.platform.win32.COM.util.office.excel.ComIWorkbook) Factory(com.sun.jna.platform.win32.COM.util.Factory) ComExcel_Application(com.sun.jna.platform.win32.COM.util.office.excel.ComExcel_Application) VARIANT(com.sun.jna.platform.win32.Variant.VARIANT) File(java.io.File) ComIApplication(com.sun.jna.platform.win32.COM.util.office.excel.ComIApplication) ComIWorksheet(com.sun.jna.platform.win32.COM.util.office.excel.ComIWorksheet)

Example 2 with ComIApplication

use of com.sun.jna.platform.win32.COM.util.office.word.ComIApplication in project jna by java-native-access.

the class MSOfficeExcelDemo method testExcel.

public static void testExcel() throws IOException {
    File demoDocument = null;
    ComIApplication msExcel = null;
    Factory factory = new Factory();
    try {
        System.out.println("Files in temp dir: " + Helper.tempDir.getAbsolutePath());
        ComExcel_Application excelObject = factory.createObject(ComExcel_Application.class);
        msExcel = excelObject.queryInterface(ComIApplication.class);
        System.out.println("MSExcel version: " + msExcel.getVersion());
        msExcel.setVisible(true);
        Helper.sleep(5);
        demoDocument = Helper.createNotExistingFile("jnatest", ".xls");
        Helper.extractClasspathFileToReal("/com/sun/jna/platform/win32/COM/util/office/resources/jnatest.xls", demoDocument);
        ComIWorkbook workbook = msExcel.getWorkbooks().Open(demoDocument.getAbsolutePath());
        msExcel.getActiveSheet().getRange("A1").setValue("Hello from JNA!");
        // wait 1sec. before closing
        Helper.sleep(1);
        // Save document into temp and close
        File output = new File(Helper.tempDir, "jnatest.xls");
        output.delete();
        workbook.SaveAs(output.getAbsolutePath());
        msExcel.getActiveWorkbook().Close(false);
        //			// msExcel.newExcelBook();
        msExcel.getWorkbooks().Open(output.getAbsolutePath());
        msExcel.getActiveSheet().getRange("A2").setValue("Hello again from JNA!");
        class Listener extends AbstractComEventCallbackListener implements ComIAppEvents {

            volatile boolean SheetSelectionChange_called;

            @Override
            public void errorReceivingCallbackEvent(String message, Exception exception) {
            }

            @Override
            public void SheetSelectionChange(ComIWorksheet sheet, ComIRange target) {
                SheetSelectionChange_called = true;
            }
        }
        ;
        Listener listener = new Listener();
        IComEventCallbackCookie cookie = msExcel.advise(ComIAppEvents.class, listener);
        Helper.sleep(1);
        msExcel.getActiveSheet().getRange("A5").Activate();
        Helper.sleep(1);
        msExcel.unadvise(ComIAppEvents.class, cookie);
        System.out.println("Listener was fired: " + listener.SheetSelectionChange_called);
        // close and discard changes
        msExcel.getActiveWorkbook().Close(false);
    } finally {
        // Make sure the excel instance is shut down
        if (null != msExcel) {
            msExcel.Quit();
        }
        // Release all objects acquired by the factory
        factory.disposeAll();
        if (demoDocument != null && demoDocument.exists()) {
            demoDocument.delete();
        }
    }
}
Also used : ComIRange(com.sun.jna.platform.win32.COM.util.office.excel.ComIRange) AbstractComEventCallbackListener(com.sun.jna.platform.win32.COM.util.AbstractComEventCallbackListener) ComIWorkbook(com.sun.jna.platform.win32.COM.util.office.excel.ComIWorkbook) AbstractComEventCallbackListener(com.sun.jna.platform.win32.COM.util.AbstractComEventCallbackListener) Factory(com.sun.jna.platform.win32.COM.util.Factory) IOException(java.io.IOException) IComEventCallbackCookie(com.sun.jna.platform.win32.COM.util.IComEventCallbackCookie) ComIWorksheet(com.sun.jna.platform.win32.COM.util.office.excel.ComIWorksheet) ComExcel_Application(com.sun.jna.platform.win32.COM.util.office.excel.ComExcel_Application) File(java.io.File) ComIApplication(com.sun.jna.platform.win32.COM.util.office.excel.ComIApplication) ComIAppEvents(com.sun.jna.platform.win32.COM.util.office.excel.ComIAppEvents)

Example 3 with ComIApplication

use of com.sun.jna.platform.win32.COM.util.office.word.ComIApplication in project jna by java-native-access.

the class MSOfficeWordDemo method testMSWord.

public static void testMSWord() throws IOException {
    File demoDocument = null;
    ComIApplication msWord = null;
    Factory factory = new Factory();
    try {
        System.out.println("Files in temp dir: " + Helper.tempDir.getAbsolutePath());
        ComWord_Application msWordObject = factory.createObject(ComWord_Application.class);
        msWord = msWordObject.queryInterface(ComIApplication.class);
        System.out.println("MSWord version: " + msWord.getVersion());
        msWord.setVisible(true);
        demoDocument = Helper.createNotExistingFile("jnatest", ".doc");
        Helper.extractClasspathFileToReal("/com/sun/jna/platform/win32/COM/util/office/resources/jnatest.doc", demoDocument);
        msWord.getDocuments().Open(demoDocument.getAbsolutePath());
        Helper.sleep(5);
        msWord.getSelection().TypeText("Hello from JNA! \n\n");
        // wait 10sec. before closing
        Helper.sleep(10);
        // save in different formats
        // pdf format is only supported in MSWord 2007 and above
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestSaveAs.doc").getAbsolutePath(), WdSaveFormat.wdFormatDocument);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestSaveAs.pdf").getAbsolutePath(), WdSaveFormat.wdFormatPDF);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestSaveAs.rtf").getAbsolutePath(), WdSaveFormat.wdFormatRTF);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestSaveAs.html").getAbsolutePath(), WdSaveFormat.wdFormatHTML);
        // close and don't save the changes
        msWord.getActiveDocument().Close(false);
        // Create a new document
        msWord.getDocuments().Add();
        // msWord.openDocument(currentWorkingDir + "jnatest.doc", true);
        msWord.getSelection().TypeText("Hello from JNA! \n Please notice that JNA can control " + "MS Word via the new COM interface! \nHere we are " + "creating a new word document and we save it " + "to the 'TEMP' directory!");
        // save with no user prompt
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestNewDoc1.docx").getAbsolutePath(), WdSaveFormat.wdFormatDocumentDefault);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestNewDoc2.docx").getAbsolutePath(), WdSaveFormat.wdFormatDocumentDefault);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestNewDoc3.docx").getAbsolutePath(), WdSaveFormat.wdFormatDocumentDefault);
        // close and don't save the changes
        msWord.getActiveDocument().Close(false);
        // open 3 documents
        msWord.getDocuments().Open(new File(Helper.tempDir, "jnatestNewDoc1.docx").getAbsolutePath());
        msWord.getSelection().TypeText("Hello some changes from JNA!\n");
        msWord.getDocuments().Open(new File(Helper.tempDir, "jnatestNewDoc2.docx").getAbsolutePath());
        msWord.getSelection().TypeText("Hello some changes from JNA!\n");
        msWord.getDocuments().Open(new File(Helper.tempDir, "jnatestNewDoc3.docx").getAbsolutePath());
        msWord.getSelection().TypeText("Hello some changes from JNA!\n");
        // save the document and prompt the user
        msWord.getDocuments().Save(false, WdOriginalFormat.wdPromptUser);
    } finally {
        // Make sure the word instance is shut down
        if (msWord != null) {
            msWord.Quit();
        }
        // Release all objects acquired by the factory
        factory.disposeAll();
        if (demoDocument != null && demoDocument.exists()) {
            demoDocument.delete();
        }
    }
}
Also used : ComWord_Application(com.sun.jna.platform.win32.COM.util.office.word.ComWord_Application) Factory(com.sun.jna.platform.win32.COM.util.Factory) File(java.io.File) ComIApplication(com.sun.jna.platform.win32.COM.util.office.word.ComIApplication)

Example 4 with ComIApplication

use of com.sun.jna.platform.win32.COM.util.office.word.ComIApplication in project jna by java-native-access.

the class Wordautomation_KB_313193_Mod method main.

public static void main(String[] args) throws IOException {
    // Initialize COM Subsystem
    Ole32.INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_MULTITHREADED);
    // Initialize Factory for COM object creation
    Factory fact = new Factory();
    try {
        // oEndOfDoc is a predefined bookmark
        final String oEndOfDoc = "\\endofdoc";
        /* \endofdoc is a predefined bookmark */
        // Start word application
        ComWord_Application word = fact.createObject(ComWord_Application.class);
        ComIApplication wordApp = word.queryInterface(ComIApplication.class);
        // Make word visible/invisible (invisible is default)
        wordApp.setVisible(true);
        // Create an empty document (signiture of depends on bindings)
        ComIDocument doc = wordApp.getDocuments().Add();
        Helper.sleep(5);
        //Insert a paragraph at the beginning of the document.
        Paragraph para1 = doc.getContent().getParagraphs().Add(VARIANT_MISSING);
        para1.getRange().setText("Heading 1");
        para1.getRange().getFont().setBold(1);
        //24 pt spacing after paragraph.
        para1.getFormat().setSpaceAfter(24F);
        para1.getRange().InsertParagraphAfter();
        //Insert a paragraph at the end of the document.
        Paragraph para2 = doc.getContent().getParagraphs().Add(doc.getBookmarks().Item(oEndOfDoc).getRange());
        para2.getRange().setText("Heading 2");
        para2.getFormat().setSpaceAfter(6F);
        para2.getRange().InsertParagraphAfter();
        //Insert another paragraph.
        Paragraph para3 = doc.getContent().getParagraphs().Add(doc.getBookmarks().Item(oEndOfDoc).getRange());
        para3.getRange().setText("This is a sentence of normal text. Now here is a table:");
        para3.getRange().getFont().setBold(0);
        para3.getFormat().setSpaceAfter(24F);
        para3.getRange().InsertParagraphAfter();
        //Insert a 3 x 5 table, fill it with data, and make the first row
        //bold and italic.
        Table table = doc.getTables().Add(doc.getBookmarks().Item(oEndOfDoc).getRange(), 3, 5, VARIANT_MISSING, VARIANT_MISSING);
        table.getRange().getParagraphFormat().setSpaceAfter(6F);
        for (int r = 1; r <= 3; r++) {
            for (int c = 1; c <= 5; c++) {
                String strText = "r" + r + "c" + c;
                table.Cell(r, c).getRange().setText(strText);
            }
        }
        table.getRows().Item(1).getRange().getFont().setBold(1);
        table.getRows().Item(1).getRange().getFont().setItalic(1);
        //Add some text after the table.
        Paragraph para4 = doc.getContent().getParagraphs().Add(doc.getBookmarks().Item(oEndOfDoc).getRange());
        para4.getRange().InsertParagraphBefore();
        para4.getRange().setText("And here's another table:");
        para4.getFormat().setSpaceAfter(24F);
        para4.getRange().InsertParagraphAfter();
        //Insert a 5 x 2 table, fill it with data, and change the column widths.
        table = doc.getTables().Add(doc.getBookmarks().Item(oEndOfDoc).getRange(), 5, 2, VARIANT_MISSING, VARIANT_MISSING);
        table.getRange().getParagraphFormat().setSpaceAfter(6F);
        for (int r = 1; r <= 5; r++) {
            for (int c = 1; c <= 2; c++) {
                String strText = "r" + r + "c" + c;
                table.Cell(r, c).getRange().setText(strText);
            }
        }
        //Change width of columns 1 & 2
        table.getColumns().Item(1).setWidth(wordApp.InchesToPoints(2F));
        table.getColumns().Item(2).setWidth(wordApp.InchesToPoints(3F));
        //Keep inserting text. When you get to 7 inches from top of the
        //document, insert a hard page break.
        Range wrdRng;
        float dPos = wordApp.InchesToPoints(7F);
        doc.getBookmarks().Item(oEndOfDoc).getRange().InsertParagraphAfter();
        do {
            wrdRng = doc.getBookmarks().Item(oEndOfDoc).getRange();
            wrdRng.getParagraphFormat().setSpaceAfter(6F);
            wrdRng.InsertAfter("A line of text");
            wrdRng.InsertParagraphAfter();
        } while (dPos >= (Float) wrdRng.getInformation(WdInformation.wdVerticalPositionRelativeToPage));
        wrdRng.Collapse(WdCollapseDirection.wdCollapseEnd);
        wrdRng.InsertBreak(WdBreakType.wdPageBreak);
        wrdRng.Collapse(WdCollapseDirection.wdCollapseEnd);
        wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
        wrdRng.InsertParagraphAfter();
        //Insert a chart and change the chart.
        InlineShape oShape = doc.getBookmarks().Item(oEndOfDoc).getRange().getInlineShapes().AddOLEObject("MSGraph.Chart.8", "", Boolean.FALSE, Boolean.FALSE, VARIANT_MISSING, VARIANT_MISSING, VARIANT_MISSING, VARIANT_MISSING);
        //Demonstrate use of late bound oChart and oChartApp objects to
        //manipulate the chart object with MSGraph.
        IDispatch oChart = oShape.getOLEFormat().getObject();
        IDispatch oChartApp = oChart.getProperty(IDispatch.class, "Application");
        //Change the chart type to Line
        oChart.setProperty("ChartType", XlChartType.xlLine.getValue());
        //Update the chart image and quit MSGraph.
        oChartApp.invokeMethod(Void.class, "Update");
        oChartApp.invokeMethod(Void.class, "Quit");
        //... If desired, you can proceed from here using the Microsoft Graph 
        //Object model on the oChart and oChartApp objects to make additional
        //changes to the chart.
        //Set the width of the chart.
        oShape.setWidth(wordApp.InchesToPoints(6.25f));
        oShape.setHeight(wordApp.InchesToPoints(3.57f));
        //Add text after the chart.
        wrdRng = doc.getBookmarks().Item(oEndOfDoc).getRange();
        wrdRng.InsertParagraphAfter();
        wrdRng.InsertAfter("THE END.");
        File tempFile = Helper.createNotExistingFile("KB_313193_", ".pdf");
        doc.ExportAsFixedFormat(tempFile.getAbsolutePath(), WdExportFormat.wdExportFormatPDF, Boolean.FALSE, WdExportOptimizeFor.wdExportOptimizeForOnScreen, WdExportRange.wdExportAllDocument, null, null, WdExportItem.wdExportDocumentContent, Boolean.FALSE, Boolean.TRUE, WdExportCreateBookmarks.wdExportCreateNoBookmarks, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, VARIANT_MISSING);
        System.out.println("Output written to: " + tempFile.getAbsolutePath());
        doc.Close(WdSaveOptions.wdDoNotSaveChanges, VARIANT_MISSING, VARIANT_MISSING);
        wordApp.Quit();
    } finally {
        fact.disposeAll();
        Ole32.INSTANCE.CoUninitialize();
    }
}
Also used : InlineShape(com.sun.jna.platform.win32.COM.util.office.word.InlineShape) Table(com.sun.jna.platform.win32.COM.util.office.word.Table) ComIDocument(com.sun.jna.platform.win32.COM.util.office.word.ComIDocument) Factory(com.sun.jna.platform.win32.COM.util.Factory) WdExportRange(com.sun.jna.platform.win32.COM.util.office.word.WdExportRange) Range(com.sun.jna.platform.win32.COM.util.office.word.Range) Paragraph(com.sun.jna.platform.win32.COM.util.office.word.Paragraph) ComWord_Application(com.sun.jna.platform.win32.COM.util.office.word.ComWord_Application) IDispatch(com.sun.jna.platform.win32.COM.util.IDispatch) File(java.io.File) ComIApplication(com.sun.jna.platform.win32.COM.util.office.word.ComIApplication)

Aggregations

Factory (com.sun.jna.platform.win32.COM.util.Factory)4 File (java.io.File)4 ComExcel_Application (com.sun.jna.platform.win32.COM.util.office.excel.ComExcel_Application)2 ComIApplication (com.sun.jna.platform.win32.COM.util.office.excel.ComIApplication)2 ComIWorkbook (com.sun.jna.platform.win32.COM.util.office.excel.ComIWorkbook)2 ComIWorksheet (com.sun.jna.platform.win32.COM.util.office.excel.ComIWorksheet)2 ComIApplication (com.sun.jna.platform.win32.COM.util.office.word.ComIApplication)2 ComWord_Application (com.sun.jna.platform.win32.COM.util.office.word.ComWord_Application)2 AbstractComEventCallbackListener (com.sun.jna.platform.win32.COM.util.AbstractComEventCallbackListener)1 IComEventCallbackCookie (com.sun.jna.platform.win32.COM.util.IComEventCallbackCookie)1 IDispatch (com.sun.jna.platform.win32.COM.util.IDispatch)1 ComIAppEvents (com.sun.jna.platform.win32.COM.util.office.excel.ComIAppEvents)1 ComIRange (com.sun.jna.platform.win32.COM.util.office.excel.ComIRange)1 ComIDocument (com.sun.jna.platform.win32.COM.util.office.word.ComIDocument)1 InlineShape (com.sun.jna.platform.win32.COM.util.office.word.InlineShape)1 Paragraph (com.sun.jna.platform.win32.COM.util.office.word.Paragraph)1 Range (com.sun.jna.platform.win32.COM.util.office.word.Range)1 Table (com.sun.jna.platform.win32.COM.util.office.word.Table)1 WdExportRange (com.sun.jna.platform.win32.COM.util.office.word.WdExportRange)1 SAFEARRAY (com.sun.jna.platform.win32.OaIdl.SAFEARRAY)1