Using JCOM in Java to operate Office objects

Source: Internet
Author: User

By using COM technology, we can use Microsoft Office applications to build many Application Extensions, however, Java developers cannot enjoy the convenience it brings-unless they have a convenient Java ACCESS to COM (Java-to-COM Bridge ). When using JCom, you can control almost all COM objects in Java, and it also has some powerful auxiliary classes for Excel.

Every time you write an application that uses an HTML table style or a Java table object to display data, the "export to Excel" function is usually required. Then the headache arises. How can this function be implemented? Can the HTML display be processed in Office 2003? Not so good! You must also support Office 97!

You can only find a tool that meets your current needs, but then you will receive more requirements. "Can this be done in Word? Can Powerpoint do this? Can I use a modem to dial up a remote server and publish data? What does Java mean by failing to implement these functions? Java can implement any function. "

Thanks to the framework component that serves as a bridge between Java and COM, it enables you to answer "Yes" when encountering these situations ". The Java-COM bridge allows you to operate Windows Components Based on your needs-previously the territory of VB, C ++, And. NET developers. By implementing a Java front-end (front end) that communicates with the DCOM back-end, you can stay away from the end-to-end COM system. At the end of this article, you can use one of the Java-to-COM bridges: It can be named JCom.

 Basic Excel knowledge

Before you start, you need to download the API from the Sourceforge website. It contains all the source code, C ++ code, and JCom of the Java class used by JCom to configure the compiled DLL of Java and COM. Put this DLL under the/bin/directory of your Java main directory. Otherwise, problems may occur. In addition, to avoid any problems, you must set the JAVA_HOME environment variable correctly. Most JCom documents are currently written in Japanese, but the translation work is in progress, so there will be some improvements in the future.

After the download and installation are complete, use the code in List 1 to try it. This code is used to create a JCom interface for Excel and write "Hello World" to the first cell. You can see the result shown in 1. Although JCom is a general COM class library, it still has many auxiliary classes for Excel, because Excel may be the most commonly used automated COM application. These helper classes can save us a lot of time, and they make JCOM a better class library.

List 1: getting started with JCOM and Excel

Import jp. ne. so_net.ga2.no_ji.jcom.excel8 .*;
Import jp. ne. so_net.ga2.no_ji.jcom .*;

Public class testSimple
{
Public static void main (String [] args) throws Exception {
ReleaseManager rm = new ReleaseManager ();
Try {
System. out. println ("EXCEL is Starting ...");
ExcelApplication excel = new ExcelApplication (rm );
Excel. Visible (true );
ExcelWorkbooks xlBooks = excel. Workbooks ();
ExcelWorkbook xlBook = xlBooks. Add ();
ExcelWorksheets xlSheets = xlBook. Worksheets ();
ExcelWorksheet xlSheet = xlSheets. Item (1 );
ExcelRange xlRange = xlSheet. Cells ();
XlRange. Item (1, 1). Value ("Hello, World! ");
}
Catch (Exception e) {e. printStackTrace ();}
Finally {rm. release ();}
}
}



Figure 1: Java uses Excel's first COM automation

If you have used VB or VBA to automate Excel, you should be familiar with the code in List 1. The ExcelApplication class exposes the Workbooks () attribute, which lists the currently opened Workbooks in Excel and allows you to add or delete Workbooks to or from running Excel copies. Use the. Add () method to Add the working thin. This method returns a reference of the working thin.

The workbook in Excel is used to save the input data. The working thin is the basis of the XLS file. A Workbook consists of multiple worksheets (three in Figure 1, Sheet1, Sheet2, and Sheet3 ). The worksheet is enumerated by the Item attribute. You can use this property to access a specific worksheet. In Figure 1, Sheet 1 is the first worksheet, so you can use xlSheets. Item (1) to obtain references to it.

With a worksheet, you can use range to operate the data on it. Range is a cell or multiple cells. For example, cell A1 can be referenced using range (1, 1), and then data can be loaded into cells using the Value attribute.

 More meaningful examples

Suppose you want to use Excel as the presentation layer of some data in the database. In Java, you want to obtain data through JDBC and display the data on the Excel front-end. This assumption is good because use cases in complex business logic are already displayed on the Excel front end, not to mention the display and interaction of other data items in the workflow. Now you don't need to understand the business logic or analysis, you can use the original spreadsheet and use Automation in Java to "fill in the cracks between them ".

I will give a simple example to demonstrate this operation: the content contained in this article is a simple MySQL database that establishes a relatively sales behavior. It has three tables:

· Sales is the Sales details, including the Sales item, quantity, Sales price, who sells and the Sales region.

· People includes the name and commission of the salesperson.

· Districts contains the name and tax rate of the sales region.

When generating a report, you need to use the following business logic to calculate the true value:

· Gross sales equals to the sales item multiplied by the sales price plus the local tax amount.

· Pure sales equals to gross sales minus the pre-tax Commission drawn by sales personnel.

This is a simple and direct computing process that can be implemented in Java, but I use them in this article to demonstrate how to write the data into an Excel spreadsheet and enable automatic Excel computing. The same applies to more complex cases (using more complex Excel formulas.

In addition, the downloaded content also contains the workbook 2. It is a workbook for you to fill in the appropriate data as a "template.



Figure 2: Excel template for filling data at the front end

When using JCOM, the following SQL statement is used to query all sales data in the database:

SELECT sales. id, sales. description, sales. quantity, sales. price, districts. districtname, districts. salestax, people. name, people. commission
FROM 'sales', 'dids', 'people'
WHERE (sales. district = districts. id) AND (sales. salesperson = people. id)

Then, use automation to write each record to an appropriate column in an Excel worksheet. The downloaded content contains the complete code (List 2 ). In the following section, I will explain for you how to use JCOM automation in the code.

List 2: Get data from the database and load the code in Excel

// Create an Excel reference
ExcelApplication excel = new ExcelApplication (rm );
// Make it visible
Excel. Visible (true );
// Then open the template worksheet we will use.
ExcelWorkbooks xlBooks = excel. Workbooks ();
ExcelWorkbook xlBook = xlBooks. Open ("c: \ sales.xls ");
// Obtain the reference of the scope to be modified.
ExcelWorksheets xlSheets = xlBook. Worksheets ();
ExcelWorksheet xlSheet = xlSheets. Item (1 );
ExcelRange xlRange = xlSheet. Cells ();

...
// Place the database link and query creation code here
...

If (stmt.exe cute (strSql ))
{
Rs = stmt. getResultSet ();
}
Int nColCount = rs. getMetaData (). getColumnCount ();
Int nRow = 1;
Int nCol = 0;
// Loop in the record set
While (rs. next ())
{
// Each row in the record set is a row in the workbook.
NRow ++;
For (int I = 1; I <= nColCount; I ++)
{
// Match DB columns and workbooks.
NCol = getExcelColumn (I );
// Find the cell corresponding to the row and column, and set it as an appropriate record set field
XlRange. Item (nRow, nCol). Value (rs. getObject (I). toString ());
}
// Enter the formula
XlRange. Item (nRow, 7). Value ("= RC [-2] * RC [-1]");
XlRange. Item (nRow, 9). Value ("= RC [-2] * RC [-1]/100 ");
XlRange. Item (nRow, 10). Value ("= RC [-3] + RC [-1]");
XlRange. Item (nRow, 11). Value ("= RC [-4] * (100-RC [2])/100 )");
}


In the first part of List 2, the target is to obtain control of the cells to be modified. This consumes a certain amount of money.

· First, you must obtain the Excel object. With the help of the JCOM auxiliary class, this step is quite direct.

ExcelApplication excel = new ExcelApplication (rm );
  
· Next, you want to obtain access to the workbook set. You want to open your template Workbook (in this example, this template is in C: sales.xls) and open it in the workbook collection.

ExcelWorkbooks xlBooks = excel. Workbooks ();

· Next, you want to open your workbook and obtain the reference of the workbook set.

ExcelWorkbook xlBook = xlBooks. Open ("c: \ sales.xls ");
ExcelWorksheets xlSheets = xlBook. Worksheets ();

· Finally, you want to get the first worksheet in the set and define the work scope as the whole worksheet.

ExcelWorksheet xlSheet = xlSheets. Item (1 );
ExcelRange xlRange = xlSheet. Cells ();

After completing these tasks, your xlRange object will allow you to put values and formulas in the unit. You can use xlRange in the previous record set (returned from the SQL command submitted to the database. item (nRow, nCol ). value ("whatever") syntax, insert the values in the record set into a workbook row by row (the whatever in the syntax comes from the record set ). You can use rs. getObject (I). toString to obtain the value of column I in the current row. By using rs. movenext (), the current row moves backward until the end of the record set.

You may notice a strange function call in List 2:

NCol = getExcelColumn (I );

This is a simple auxiliary function that matches the column number in the record set with the position where the data is stored in Excel. For example, if you view the preceding SQL statement again, the commission rate is returned to the 8th column. In a workbook, it contains 13th columns. This function is used to process the conversion between the two. More complex applications can use the named range in Excel to match columns, but this is beyond the scope of this article.

Finally, the application enters the formula into an appropriate unit. It is implemented using the R1C1 symbol of Excel, so the corresponding string is used to describe the formula. In Excel, suppose you want to add the value of column A in row 1st to the value of Column B, and then put it in Column C, enter the formula "= A1 + B1" in Column C ". If you want this operation in the second line, you can copy and paste the formula, which is automatically updated to "= A2 + B2 ".

Some string operations are required to obtain these values from the sample program. However, if you use "R1C1"-related conversions, they are very straightforward. In the example in this article, when you enter a formula in C1, you do not need to provide a reference to "= A1 + B1, instead, the reference "= RC [-2] + RC [-1]" is given, which means to add the values of the first two columns to the values of the first column.

When you move other rows, the value of this formula will not change, so it makes the values required for generating programs very simple. This is also my method for calculating total sales, sales taxes, gross sales, and pure sales, as shown below:

XlRange. Item (nRow, 7). Value ("= RC [-2] * RC [-1]");
XlRange. Item (nRow, 9). Value ("= RC [-2] * RC [-1]/100 ");
XlRange. Item (nRow, 10). Value ("= RC [-3] + RC [-1]");
XlRange. Item (nRow, 11). Value ("= RC [-4] * (100-RC [2])/100 )");

Run this code to obtain the workbook shown in figure 3.


Figure 3: formula: Excel displays the output information of the database query.

Please note that this is a good engineering experience, that is, do not include formulas in the application, because the formulas may change at any time, you certainly do not want to change your code when changing the formula. This method makes each new data row a copy of an existing data row that contains the formula. The template spreadsheet (sales.xls) contains false data and the formula (the first column contains the column title) in the second column ). Therefore, when you fill in each row, copy the content of this row before you fill in the database value. In this way, formulas are copied into new data rows, and you do not need to include any business logic in Java code.

Let's take a look at the content in the salesReport2.java file (which is also being downloaded). You can see that we didn't use the formula mentioned above, but used the following code at the top of the While loop:

If (nRow> 1)
{
String strDest = "A" + (nRow + 1 );
ExcelRange xlRange2Copy = xlSheet. Range ("A2: M2 ");
XlRange2Copy. Copy (xlSheet. Range (strDest ));
}

In addition to the first line (this information is included in sales.xls), this code processes the units between A2 and M2 and copies them to the data row marked by nRow + 1 (nRow is the number of the current row ). The reason for adding 1 is that the column title is calculated (the column title is in the first row ).

  Excel

Remember that JCOM is used for COM, not just for Excel. You can use this tool to control almost all COM objects in Java. Excel is the most common object to be controlled, because there are many good helper classes that can make it easier, but all COM components can be used. Therefore, controlling other applications (such as Word and Powerpoint) is also direct.

The following is an example of using Word:

IDispatch wdApp = new IDispatch (rm, "Word. Application ");
WdApp. put ("Visible", new Boolean (true ));

Because there is no direct helper class for Word, each part must be implemented by using the IDispatch object (the lower-level helper class for Excel is also implemented in this way ). The above code is loaded into a copy of Microsoft Word and can be automatically operated by wdApp objects. Then, you can use methods such as "put" (set attribute) or "method" (call method) to use Word. For example, the code above sets the Visible attribute to true to make the Word application Visible.

If you must use Windows, a large number of COM components can expand your horizons. The number of COM components is much larger than that currently provided by Java. Hardware control through serial and parallel ports can also be implemented in Java, which is just the beginning. After JCOM is available in your toolkit, there will be no restrictions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.