使用Java在MS Word文件中创建表

时间:2008-12-30 08:05:05

标签: java ms-word

我想使用Java在Microsoft Office Word文件中创建一个表。任何人都可以通过一个例子告诉我如何做到这一点吗?

9 个答案:

答案 0 :(得分:5)

查看Apache POI

  

POI项目是主项目   用于开发纯Java端口的文件   格式基于Microsoft的OLE 2   复合文档格式。 OLE 2   复合文档格式由。使用   Microsoft Office文档,以及   由使用MFC属性集的程序   序列化他们的文档对象。

答案 1 :(得分:2)

我从来没有见过它,而且我在Word中工作了很多。如果您真的想以编程方式在word文档中执行某些操作,那么我建议使用专门为此目的而设计的Microsoft脚本语言VBA。事实上,我现在正在努力。

如果你在Open Office下工作,那么他们就会有一组非常相似的宏观工具来做同样的事情。

答案 2 :(得分:1)

Office 2003具有xml格式,Office 2007的默认文档格式为xml(压缩)。所以你可以从java生成xml。如果您打开一个现有文档,那么看起来也不太难看。

或者,您可以使用openoffice的api生成文档,并将其另存为ms-word文档。

答案 3 :(得分:1)

此代码段可用于在MS Word文档中动态创建表格。

WPFDocument document = new XWPFDocument();
XWPFTable tableTwo = document.createTable();
XWPFTableRow tableTwoRowOne = tableTwo.getRow(0);
tableTwoRowOne.getCell(0).setText(Knode1);
tableTwoRowOne.createCell().setText(tags.get("node1").toString());
for (int i = 1; i < nodeList.length; i++) {
    String node = "node";
    String nodeVal = "";
    XWPFTableRow tr = null;
    node = node + (i + 1);
    nodeVal = tags.get(node).toString();
    if (tr == null) {
        tr = tableTwo.createRow();
        tr.getCell(0).setText(nodeList[i]);
        tr.getCell(1).setText(tags.get(node).toString());
    }
}

答案 4 :(得分:0)

Office Writer比POI更适合您的使用。

如果您只想要一个没有太多格式化的简单表格,我会使用这个简单的技巧。使用Java使用普通旧表,tr,td标记将表生成为HTML,并将呈现的HTML表复制到word文档中;)

答案 5 :(得分:0)

我们的功能集是点击我们的网络应用程序中的按钮,然后将您正在查看的页面作为Word文档获取。我们使用docx模式来描述文档,并在服务器端拥有一堆Java代码,用于创建文档和响应我们的Web客户端。格式化本身是通过Java中的一些已编译的xsl-t来完成的,以便从我们自己的XML持久层转换。

docx架构很难理解。我们取得最大进步的方式是在Word中创建模板docx,其中包含我们需要的格式,但具有虚假内容。然后我们愚弄了他们,直到我们完全理解发生了什么。 docx中有大量您不需要担心的内容。在阅读/翻译docx时,Word非常容忍部分完整的格式化模式。事实上,我们选择删除几乎所有的格式,因为它也意味着用户的默认格式优先,他们似乎更喜欢。它还使xsl进程更快,结果文档更小。

答案 6 :(得分:0)

我管理docx4j项目

docx4j包含一个类TblFactory,它创建常规表(即没有行或列跨度),使用Word 2007将创建的默认设置,以及用户指定的维度。

如果你想要一个更复杂的表,最简单的方法是在Word中创建它,然后将生成的XML复制到IDE中的String中,在那里你可以使用docx4j的XmlUtils.unmarshalString从中创建一个Tbl对象。 / p>

答案 7 :(得分:0)

使用我的小型zip实用程序,如果您知道自己在做什么,就可以轻松创建docx。 Word的DOCX文件格式只是zip(带有xml文件的文件夹)。通过使用java zip实用程序,您可以修改现有的docx,只修改内容部分。

要使以下示例正常工作,只需打开Word,输入几行,保存文档即可。然后使用zip程序,从zip中删除文件word / document.xml(这是Word文档的主要内容所在的文件)。现在您已准备好模板。保存修改后的zip。

以下是新Word文件的创建内容:

/* docx file head  */
    final String DOCUMENT_XML_HEAD =
            "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>" +
            "<w:document xmlns:wpc=\"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:wp14=\"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:w10=\"urn:schemas-microsoft-com:office:word\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\" xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" xmlns:wpi=\"http://schemas.microsoft.com/office/word/2010/wordprocessingInk\" xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\" xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\" mc:Ignorable=\"w14 w15 wp14\">" +
            "<w:body>";

    /* docx file foot  */
    final String DOCUMENT_XML_FOOT =
             "</w:body>" +
             "</w:document>";


    final ZipOutputStream zos =  new ZipOutputStream(new FileOutputStream("c:\\TEMP\\test.docx"));

    final String fullDocumentXmlContent = DOCUMENT_XML_HEAD + "<w:p><w:r><w:t>Hey MS Word, hello from java.</w:t></w:r></w:p>" + DOCUMENT_XML_FOOT;

    final si.gustinmi.DocxZipCreator creator = new si.gustinmi.DocxZipCreator();

    // create new docx file
    creator.createDocxFromExistingDocx(zos, "c:\\TEMP\\existingDocx.docx", fullDocumentXmlContent);

这些是zip工具:

package si.gustinmi;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * Creates new docx from existing one.
 * @author gustinmi [at] gmail [dot] com
 */
public class DocxZipCreator {

    public static final Logger log = Logger.getLogger(DocxZipCreator.class.getCanonicalName());

    private static final int BUFFER_SIZE = 4096;


    /** OnTheFly zip creator. Traverses through existing docx zip and creates new one simultaneousl.
     * On the end, custom document.xml is inserted inside
     * @param zipFilePath location of existing docx template (without word/document.xml)
     * @param documentXmlContent content of the word/document.xml
     * @throws IOException
     */
    public void createDocxFromExistingDocx(ZipOutputStream zos, String zipFilePath, String documentXmlContent) throws IOException {

        final FileInputStream fis = new FileInputStream(zipFilePath);
        final ZipInputStream zipIn = new ZipInputStream(fis);

        try{
            log.info("Starting to create new docx zip");
            ZipEntry entry = zipIn.getNextEntry();
            while (entry != null) { // iterates over entries in the zip file
                copyEntryfromZipToZip(zipIn, zos, entry.getName());
                zipIn.closeEntry();
                entry = zipIn.getNextEntry();
            }

            // add document.xml to existing zip
            addZipEntry(documentXmlContent, zos, "word/document.xml");

        }finally{
            zipIn.close();
            zos.close();
            log.info("End of docx creation");
        }

    }

    /** Copies sin gle entry from zip to zip  */
    public void copyEntryfromZipToZip(ZipInputStream is, ZipOutputStream zos, String entryName)
    {
        final byte [] data = new byte[BUFFER_SIZE]; 
        int len; 
        int lenTotal = 0;
        try {

            final ZipEntry entry = new ZipEntry(entryName); 
            zos.putNextEntry(entry); 

            final CRC32 crc32 = new CRC32(); 
            while ((len = is.read(data)) > -1){ 
                zos.write(data, 0, len); 
                crc32.update(data, 0, len);
                lenTotal += len;
            } 

            entry.setSize(lenTotal); 
            entry.setTime(System.currentTimeMillis()); 
            entry.setCrc(crc32.getValue());

        }
        catch (IOException ioe){
            ioe.printStackTrace();
        }
        finally{
            try { zos.closeEntry();} catch (IOException e) {}
        }
    }

    /**  Create new zip entry with content
     * @param content content of a new zip entry
     * @param zos 
     * @param entryName name (npr: word/document.xml)
     */
    public void addZipEntry(String content, ZipOutputStream zos, String entryName)
    {
        final byte [] data = new byte[BUFFER_SIZE]; 
        int len; 
        int lenTotal = 0;
        try {

            final InputStream is = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));

            final ZipEntry entry = new ZipEntry(entryName); 
            zos.putNextEntry(entry); 

            final CRC32 crc32 = new CRC32(); 
            while ((len = is.read(data)) > -1){ 
                zos.write(data, 0, len); 
                crc32.update(data, 0, len);
                lenTotal += len;
            } 

            entry.setSize(lenTotal); 
            entry.setTime(System.currentTimeMillis()); 
            entry.setCrc(crc32.getValue());

        }
        catch (IOException ioe){
            ioe.printStackTrace();
        }
        finally{
            try { zos.closeEntry();} catch (IOException e) {}
        }
    }

}

答案 8 :(得分:-1)

点击此处查看Working example with source code。 此示例基于模板概念从Java生成MS-Word文档。