杰瑞科技汇

如何用Java操作Access的OLE对象?

Of course. Accessing OLE (Object Linking and Embedding) objects from Java is a complex task because Java does not have built-in, direct support for the OLE API. The standard Java libraries are designed to be platform-agnostic, while OLE is a core component of the Windows operating system.

如何用Java操作Access的OLE对象?-图1
(图片来源网络,侵删)

Therefore, to work with OLE in Java, you must use a Java Native Interface (JNI) bridge to call the native Windows COM (Component Object Model) API, which is the modern successor to OLE.

Here’s a comprehensive guide covering the concepts, approaches, and a practical example.


Understanding the Core Concepts

OLE vs. COM

  • OLE (Object Linking and Embedding): The original technology from the early 90s for embedding documents (like a Word document inside an Excel sheet). It's largely a legacy term now.
  • COM (Component Object Model): The underlying, more robust infrastructure that made OLE possible. When you talk to "OLE" from code today, you are almost always interacting with COM objects. For example, Microsoft Office applications (Word, Excel, etc.) expose their functionality through COM interfaces.

The Challenge for Java

Java runs in the Java Virtual Machine (JVM), which is isolated from the operating system. To call a Windows-specific API like COM, you need a "bridge" that allows Java code to call native C/C++ code.

The Solution: JNI and COM Wrappers

You don't want to write the JNI code from scratch—it's complex, platform-specific, and error-prone. Instead, you use a pre-built library that provides a Java-friendly API for accessing COM. These libraries handle the JNI plumbing for you.

如何用Java操作Access的OLE对象?-图2
(图片来源网络,侵删)

Recommended Approaches & Libraries

Here are the most common ways to access OLE/COM from Java, from the most recommended to the most complex.

Approach 1: Use a High-Level Wrapper (Recommended for Most Cases)

This is the easiest and most maintainable approach. You use a library that provides a clean API to interact with specific applications like Microsoft Office.

JACOB (Java COM Bridge)

  • Description: The most popular and widely used library for this purpose. It's a JNI-based wrapper that allows you to call COM objects from Java.
  • Pros:
    • Relatively easy to use.
    • Good documentation and a large community.
    • Works with a wide range of COM servers (Office, AutoCAD, etc.).
  • Cons:
    • Requires a native DLL (jacob.dll) to be present on the Windows machine where the code runs.
    • You are responsible for managing the COM object lifecycle (releasing memory).

Apache POI (for Office Documents)

如何用Java操作Access的OLE对象?-图3
(图片来源网络,侵删)
  • Description: While not a direct COM wrapper, Apache POI is the de-facto standard for reading and writing Microsoft Office file formats (.xls, .docx, .pptx) without needing Microsoft Office installed.
  • When to use it: If your goal is simply to create or manipulate documents, use POI. It's pure Java, much simpler, and more portable. Only use JACOB if you need to control the live application itself (e.g., automate the UI, print a document, use a feature not supported by the file format).

Approach 2: Use a Low-Level COM Library

These libraries give you more direct control over the COM API but are significantly harder to use.

J-Integra

  • Description: A commercial (with a free option) pure Java COM bridge. It doesn't require a native DLL but uses a separate proxy process.
  • Pros: Pure Java, more portable.
  • Cons: Can be more complex to set up, licensing for commercial use.

JNI with Native Code (DIY - Not Recommended)

  • Description: Writing your own JNI wrapper for the COM API.
  • Pros: Complete control.
  • Cons: Extremely complex, time-consuming, platform-specific, and difficult to maintain. Only consider this for very specialized, long-term projects where no other library will suffice.

Practical Example: Automating Microsoft Word with JACOB

Let's walk through a common task: creating a new Microsoft Word document, adding text, and saving it, all from Java using JACOB.

Step 1: Download JACOB

  1. Go to the JACOB project page on SourceForge: https://sourceforge.net/projects/jacob-project/
  2. Download the latest release (e.g., jacob-1.21.zip).
  3. Unzip the file. You will find:
    • jacob.jar: The Java library you need to add to your project's classpath.
    • jacob-1.21-x64.dll (or x86): The native library for your system architecture.

Step 2: Set Up Your Project

  • Eclipse/IntelliJ IDEA: Add jacob.jar to your project's libraries.

  • Command Line: Compile and run with the jar on the classpath:

    # Compile
    javac -cp ".;jacob.jar" YourJavaFile.java
    # Run (on Windows)
    java -cp ".;jacob.jar" YourJavaFile

Step 3: Place the DLL

The native DLL (jacob-1.21-x64.dll) must be on the system's PATH or in the same directory where you are running the Java application. The easiest way for development is to place it in your project's root folder or the src/main/resources directory (and copy it to the output folder during the build process).

Step 4: Write the Java Code

This code will create a Word instance, add a paragraph, and save the document.

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordAutomation {
    public static void main(String[] args) {
        // The constant for the Word application ProgID
        String wordProgId = "Word.Application";
        // Create a new instance of the Word Application
        ActiveXComponent wordApp = new ActiveXComponent(wordProgId);
        try {
            // Make the application visible (optional)
            wordApp.setProperty("Visible", new Variant(true));
            // Get the Documents collection
            Dispatch documents = wordApp.getProperty("Documents").toDispatch();
            // Add a new document
            Dispatch document = Dispatch.call(documents, "Add").toDispatch();
            // Get the content of the document
            Dispatch content = Dispatch.get(document, "Content").toDispatch();
            // Type some text
            Dispatch.call(content, "InsertAfter", "Hello, from Java via JACOB!");
            // Save the document
            // The first parameter is the file path, the second is the file format
            // (0 = wdFormatDocument, the default .docx format)
            Dispatch.call(document, "SaveAs", "C:\\Temp\\MyFirstJavaWord.docx", 0);
            System.out.println("Document created and saved successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // IMPORTANT: Quit the Word application to free up resources
            // If you don't do this, a WINWORD.EXE process will remain in the background.
            Variant f = new Variant(false);
            Dispatch.call(wordApp, "Quit", f);
            wordApp.safeRelease();
        }
    }
}

Step 5: Run the Code

  • Make sure Microsoft Word is installed on the machine.
  • Run the WordAutomation class.
  • A Word window should appear (because we set Visible to true), and a new document will be created.
  • After a few seconds, Word will quit, and you will find the file MyFirstWord.docx in C:\Temp.

Critical Considerations and Best Practices

  1. Error Handling and Resource Management: COM objects manage their own memory. It is CRITICAL to release all COM objects you create. The finally block is your best friend. Always call Quit on the application object and safeRelease() on all Dispatch objects when you are done. Failing to do so will leave orphaned processes running.

  2. 64-bit vs. 32-bit: You must match the architecture of your JVM, your JACOB DLL, and your Microsoft Office installation.

    • If you are running a 64-bit JVM, you need the 64-bit version of Office and the jacob-1.21-x64.dll.
    • Mixing 32-bit and 64-bit will result in UnsatisfiedLinkError.
  3. Licensing: Ensure you have the proper license to automate Microsoft Office in a server environment. The Microsoft Office license typically allows for client-side automation but may have restrictions on server-side use.

  4. Alternative: Apache POI: If you just need to create a .docx file without the overhead of starting Word, use Apache POI. It's simpler and doesn't require Office to be installed.

    // Example using Apache POI (requires poi-ooxml library)
    import org.apache.poi.xwpf.usermodel.*;
    XWPFDocument doc = new XWPFDocument();
    XWPFParagraph p = doc.createParagraph();
    XWPFRun r = p.createRun();
    r.setText("Hello, from Java via Apache POI!");
    r.setBold(true);
    try (FileOutputStream out = new FileOutputStream("C:\\Temp\\MyPOIWord.docx")) {
        doc.write(out);
    }
    System.out.println("POI document created successfully!");

Summary

Task Recommended Approach Why?
Create/Read/Edit Office files Apache POI Pure Java, no Office installation needed, simpler, more portable.
Control a live Office application (e.g., click buttons, print, use COM add-ins) JACOB (Java COM Bridge) Directly interfaces with the COM API, giving you full control.
Complex, custom Windows COM interaction J-Integra or other commercial library Offers advanced features or pure Java implementation where needed.
Building a custom COM bridge from scratch JNI + C/C++ Only for experts with very specific, long-term requirements. Avoid.
分享:
扫描分享到社交APP
上一篇
下一篇