如何使用 Java 从模板或现有文档创建 Word 文档? [英] how create a Word document from a template or existing document with Java?

查看:22
本文介绍了如何使用 Java 从模板或现有文档创建 Word 文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文档模板,其中一些字段是静态的,而另一些是动态的.我需要替换一些数据(姓名、姓氏、薪水)并生成新文件.你推荐什么图书馆来做到这一点?POI 合适吗?我正在使用 Spring、Java EE6 和 Oracle.

I have a document template where some fields are static and others are dynamic. I need to replace some data (name, last name, salary) and generate the new file. What library do you recommend to do this? Is POI appropriate? I am working with Spring, Java EE6 and Oracle.

推荐答案

您可以尝试一下 Apache POI,但是 POI 的 HWPF 和 XWPF 部分用于操作 word 文件非常复杂 - 您需要在至少对word文件的结构有很好的了解!

You can give Apache POI a try but the HWPF and XWPF part of POI which are required to manipulate word files are really complicated to use - you need to have at least a good understanding how a word file is structured!

使用 iText 和 PDF 的解决方案

我对 PDF 做了类似的事情(这可能是你的一个选择)

I did something similar with PDF (this might be an option for you)

1) 您可以使用 LibreOffice 在文档中创建字段(如在 Acrobat Pro 中)

1) You can use LibreOffice to create fields in the document (like in Acrobat Pro)

  • 创建一个 .odt 文件并为其设置样式
  • 或使用 MS Word 或 LibreOffice Writer 将您的模板转换为该模板
  • 然后转到查看"->工具栏"->表单设计"并设置打开/关闭设计模式"
  • 现在您可以向文件中添加字段(双击它会打开字段的属性)
  • 完成后:文件 -> 导出为 PDF"

2) 现在您可以使用 iText 来填写创建的字段

2) Now you can use iText to fill in the created fields

以下只是示例代码:

    public byte[] getDocumentAsByteArray(Object dataBean, String pdfTemplateName) throws KkmsException {

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PdfStamper stamp = null;
    InputStream templateInputStream = null;

    Locale local = new Locale(language);

    try {
        templateInputStream = // get the file input stream of the pdf
        PdfReader reader = new PdfReader(templateInputStream);

        // Create a stamper that will copy the document to a new file
        stamp = new PdfStamper(reader, outputStream);

        AcroFields form = stamp.getAcroFields();

        // form fields are normal text in the end
        stamp.setFormFlattening(true);
        Map<String, AcroFields.Item> map = (Map<String, AcroFields.Item>)form.getFields();
        if (map != null) {
            if (map.size() == 0) {
                logger.debug("There are no fields in this PDF layout");
            }
            for (Entry<String, AcroFields.Item> e : map.entrySet()) {
                logger.debug("PDF fieldname = " + e.getKey());

                // at the moment we only handle text fields
                if (AcroFields.FIELD_TYPE_TEXT == form.getFieldType(e.getKey())) {
                    fillForm(dataBean, form, e.getKey(), local);
                } else {
                    logger.warn("Field type is not supported: "+form.getFieldType(e.getKey()));
                }
            }
        }

        stamp.close();
    } catch (Exception e) {
        logger.warn("Failed to create PDF document", e);
        throw new KkmsException("Failed to create PDF document: "+e.getMessage());
    } finally {
        if (templateInputStream != null) {
            try {
                templateInputStream.close();
            } catch (IOException e) {
                throw new KkmsException("Failed to close InputStream of PDF document", e);
            }
        }
    }
    return outputStream.toByteArray();
}

最后你会得到一个 PDF -> 希望这至少对你有一点帮助!

In the end you get a PDF -> hope this helps you at least a little bit!

另一种快速而肮脏的解决方案

可能是使用 odt 或 docx 的强大功能 -> 将您的文档转换为 docx 或 odt -> 它只是一个 zip 文件 -> 解压它 -> 您将在 zip 的根目录中看到一个 content.xml 文件-> 里面有所有的文档内容现在您可以在此处添加一些魔术标签(例如 $$$),稍后可以将其替换为您的程序

Could be to use the power of odt or docx -> convert your doc to docx or odt -> its just a zip file -> so unzip it -> you will see a content.xml file in the root of the zip -> there is all the document content in there Now you could add some magic tags (e.g. $$$) here which can later be replaced by your program

<text:p text:style-name="P3">SAP Customer Number:</text:p>

<text:p text:style-name="P3">SAP Customer Number: $$$sapCustomerNumber$$$</text:p>

现在创建一个解压 odt/docx 文件的程序 -> 替换标签 -> 再次压缩文件

Now create a program which unzips the odt/docx file -> replaces the tags -> zips the file again

这篇关于如何使用 Java 从模板或现有文档创建 Word 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆