简体   繁体   English

如何在Java Form中嵌入Microsoft Word?

[英]How can I embed microsoft word in java Form?

I want to read a word document with the help of microsoft word but that would be limited to my java form . 我想借助Microsoft Word来阅读Word文档,但这仅限于我的Java形式。 The document will be opened in java form with the help of microsoft word . 该文档将在Microsoft Word的帮助下以Java格式打开。

Like the following picture , I want to develop something : 如下图所示,我想开发一些东西: 在此处输入图片说明

User can edit the doc according to their need . 用户可以根据需要编辑文档。 But when they want to save the document , the document will be saved in a remote machine . 但是当他们要保存文档时,文档将保存在远程计算机中。

I can open the word document with the help of microsoft word by the following code : 我可以通过以下代码在Microsoft Word的帮助下打开Word文档:

try {
            /* if (Desktop.isDesktopSupported()) {
                  Desktop.getDesktop().open(new File("E:\\finger.docx"));
             }*/
            Process p = Runtime.getRuntime()
                .exec("rundll32 url.dll,FileProtocolHandler E:\\finger.docx");
             p.waitFor(); 
            System.out.println("Done.");
        } catch (IOException ioe) {
              ioe.printStackTrace();
        }
        catch (InterruptedException ex) {
                Logger.getLogger(JavaFromWord.class.getName()).log(Level.SEVERE, null, ex);
            }

But I do not know how can I embed the word viewer in JForm . 但是我不知道如何将单词查看器嵌入JForm中。 Please help me . 请帮我 。

As others have pointed out, this sounds a lot like an XY problem—meaning, you have already decided that the best solution is using Microsoft Word, so you are asking how to embed Microsoft Word instead of asking about your actual goal, which appears to be incorporating formatted text in a user interface. 正如其他人指出的那样,这听起来很像XY问题-意味着,您已经确定最佳的解决方案是使用Microsoft Word,因此您正在询问如何嵌入Microsoft Word,而不是询问您的实际目标,将格式化的文本合并到用户界面中。

A good way to do this is with a JEditorPane containing HTML content: 一个很好的方法是使用包含HTML内容的JEditorPane:

import java.awt.EventQueue;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

public class HtmlPane {
    static void show() {
        JEditorPane content = new JEditorPane("text/html",
            "<p>" +
            "The process of finger enrollment is now to be done in database." +
            " Previously it was done in file template." +
            " There are several reasons behind this:" +
            "<ol>" +
            "<li>" +
            "Time:<br>" +
            "--------" +
            "<p>" +
            "The process of verification in file template based method takes" +
            " 6.9 s on average.  On the other hand, in database based method," +
            " it takes only 3.5 s." +
            "<p>" +
            "The code for determining time is as follows:" +
            "<blockquote>" +
            "<pre>" +
            "Dim StartTime, Elapsed Time\n" +
            "StartTime = Timer\n" +
            "ElapsedTime = Timer.CheckTime\n" +
            "</pre>" +
            "</blockquote>" +
            "</ol>");

        content.setEditable(false);

        JFrame frame = new JFrame("finger");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JScrollPane(content));

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> show());
    }
}

(Note: The Swing HTML renderer only supports HTML 3.2.) (注意:Swing HTML渲染器仅支持HTML 3.2。)

If you aren't familiar with HTML, I advise you to learn it. 如果您不熟悉HTML,建议您学习它。 Basic HTML is very easy to write. 基本的HTML 容易编写。 Plus, you need to know basic HTML to be an effective Java programmer, because professional development requires writing javadoc, and all javadoc is in HTML. 另外,您需要了解基本的HTML才能成为有效的Java程序员,因为专业开发需要编写javadoc,并且所有javadoc都使用HTML。

I have succeeded to do this job . 我已经成功完成了这项工作。 The following code helps me a lot to do it . 以下代码对我有很大帮助。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleClientSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;

import com.connect.DBConnectionHandler;

public class SWTMenuExample {
    static OleClientSite clientSite;
    static OleFrame frame;
    static File file;
    static Shell shell;
    static KeyListener keyListener;
    static Display display;

    public static void main(final String[] args) {
        display = new Display();
        shell = new Shell(display);

        shell.setSize(800, 600);
        shell.setText("Word Example");
        shell.setLayout(new FillLayout());

        try {
            frame = new OleFrame(shell, SWT.NONE);
            // esto abre un documento existente
            // clientSite = new OleClientSite(frame, SWT.NONE, new
            // File("Doc1.doc"));
            // esto abre un documento en blanco
            // clientSite = new OleClientSite(frame, SWT.NONE, "Word.Document");
            addFileMenu(frame);
            System.out.println(" I am in run method ");
        } catch (final SWTError e) {
            System.out.println("Unable to open activeX control");
            display.dispose();
            return;
        }

        keyListener = new KeyListener() {

            public void keyReleased(KeyEvent paramKeyEvent) {

            }

            public void keyPressed(KeyEvent paramKeyEvent) {
                // TODO Auto-generated method stub
                if (((paramKeyEvent.stateMask & SWT.CTRL) == SWT.CTRL)
                        && (paramKeyEvent.keyCode == 's')) {
                    JOptionPane.showMessageDialog(null,
                            "ctrl+s is pressed down initial ",
                            "Warning Message", JOptionPane.WARNING_MESSAGE);
                    if (file != null) {
                        clientSite.save(file, true);
                        fileSave();
                        JOptionPane.showMessageDialog(null,
                                "ctrl+s is pressed down", "Warning Message",
                                JOptionPane.WARNING_MESSAGE);
                    } else
                        JOptionPane.showMessageDialog(null, "File is null",
                                "Warning Message", JOptionPane.WARNING_MESSAGE);
                }

            }
        };

        display.addFilter(SWT.KeyDown, new Listener() {

            public void handleEvent(Event e) {
                if (((e.stateMask & SWT.CTRL) == SWT.CTRL)
                        && (e.keyCode == 's')) {
                    System.out.println("From Display I am the Key down !!"
                            + e.keyCode);
                }
            }
        });

        final Color green = display.getSystemColor(SWT.COLOR_GREEN);
        final Color orig = shell.getBackground();

        shell.addKeyListener(new KeyListener() {
            public void keyReleased(KeyEvent e) {
                if (((e.stateMask & SWT.CTRL) == SWT.CTRL)
                        && (e.keyCode == 's')) {
                    shell.setBackground(orig);
                    System.out.println("Key up !!");
                }
            }

            public void keyPressed(KeyEvent e) {
                if (((e.stateMask & SWT.CTRL) == SWT.CTRL)
                        && (e.keyCode == 's')) {
                    shell.setBackground(green);
                    System.out.println("Key down !!");
                }
            }
        });

        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }

    static void addFileMenu(OleFrame frame) {
        final Shell shell = frame.getShell();
        Menu menuBar = shell.getMenuBar();
        if (menuBar == null) {
            menuBar = new Menu(shell, SWT.BAR);
            shell.setMenuBar(menuBar);
        }
        MenuItem fileMenu = new MenuItem(menuBar, SWT.CASCADE);
        fileMenu.setText("&File");
        Menu menuFile = new Menu(fileMenu);
        fileMenu.setMenu(menuFile);
        frame.setFileMenus(new MenuItem[] { fileMenu });

        MenuItem menuFileCreate = new MenuItem(menuFile, SWT.CASCADE);
        menuFileCreate.setText("Create File");
        menuFileCreate.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                fileCreate();
            }
        });

        MenuItem menuFileOpen = new MenuItem(menuFile, SWT.CASCADE);
        menuFileOpen.setText("Open File");
        menuFileOpen.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                fileOpen();
            }
        });

        MenuItem menuFileSave = new MenuItem(menuFile, SWT.CASCADE);
        menuFileSave.setText("Save File");
        menuFileSave.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                if (file != null) {
                    clientSite.save(file, true);
                    fileSave();
                }
            }
        });

        MenuItem menuFileClose = new MenuItem(menuFile, SWT.CASCADE);
        menuFileClose.setText("Close File");
        menuFileClose.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                if (clientSite != null) {
                    clientSite.dispose();
                    file = null;
                }
            }
        });
    }

    static void fileCreate() {
        if (clientSite != null)
            clientSite.dispose();
        if (file != null)
            file.delete();
        String fileName = JOptionPane
                .showInputDialog("Please input the name of you file: ");
        if (fileName != null) {
            if (fileName.trim().equals("")) {
                JFrame frame = new JFrame(
                        "JOptionPane showMessageDialog example");

                JOptionPane.showMessageDialog(frame,
                        "File Name must have some value", "Warning Message",
                        JOptionPane.WARNING_MESSAGE);
            } else {

                Connection conn = DBConnectionHandler.getConnection();
                PreparedStatement pstmt;
                try {
                    pstmt = conn
                            .prepareStatement("insert into FILEDATA(PR_KEY, FILENAME, FILEDATA) values (seq_file.nextval,?, EMPTY_BLOB())");
                    pstmt.setString(1, fileName + ".docx");
                    pstmt.executeUpdate();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    static void fileOpen() {
        List<String> FileName = new ArrayList<String>();
        try {
            Connection conn = DBConnectionHandler.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rset = stmt.executeQuery("select FILENAME from FILEDATA");
            while (rset.next())
                FileName.add(rset.getString(1));
            System.out.println("List Size "+FileName.size());
            if (clientSite != null)
                clientSite.dispose();
            shell.setVisible(false);
            if (file != null)
                file.delete();
            SWTMenuExample swtClass = new SWTMenuExample();
            NewJFrame form = new NewJFrame(FileName, clientSite, shell, frame,
                    swtClass);
            form.setVisible(true);
            form.setSize(400, 400);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*
         * FileDialog dialog = new FileDialog(shell, SWT.OPEN);
         * dialog.setFilterExtensions(new String[] { "*.docx" }); String
         * fileName = dialog.open(); if (fileName != null) { if (clientSite !=
         * null) clientSite.dispose(); file = new File(fileName); clientSite =
         * new OleClientSite(frame, SWT.NONE, "Word.Document", file);
         * clientSite.addKeyListener(keyListener);
         * clientSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE); }
         */
    }

    void fileOpenFromDrive(File happyFile) {
        file = happyFile;
        display.asyncExec(new Runnable() {
            @Override
            public void run() {
                shell.setVisible(true);
                if (clientSite != null)
                    clientSite.dispose();

                clientSite = new OleClientSite(frame, SWT.NONE,
                        "Word.Document", file);
                clientSite.addKeyListener(keyListener);
                clientSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);

                shell.addListener(SWT.Close, new Listener() {
                    public void handleEvent(Event event) {
                        if (file != null)
                            file.delete(); 
                        shell.dispose();
                    }
                });
            }
        });

    }

    static void fileSave() {
        try {
            FileInputStream fis = new FileInputStream(file);
            Connection conn = DBConnectionHandler.getConnection();

            PreparedStatement pstmt = conn
                    .prepareStatement("update FILEDATA  set FILEDATA = ?  where FILENAME = ?");
            pstmt.setBinaryStream(1, fis, (int) file.length());
            pstmt.setString(2, file.getName());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

It will open docx as like in the following picture : 它将打开docx,如下图所示:

在此处输入图片说明

实际上,您不能在Java gui应用程序中显示任何非您的项目框架,这实际上是不真实的-您只能在JInternalFrame中显示Java框架

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM