使用Jacob合并Word文档并填充文档中的书签

JacobJava COM Bridge)是一个开始于1999年的开源项目,它支持在Java环境中调用Windows平台下的COM组件,接下来我们要使用的dll文件就是COM组件。

运行以下代码需下载jar包及dll文件 (http://sourceforge.net/projects/jacob-project/)

PS首先电脑要安装Office软件中的Word程序,容易忽视的是我们自己的电脑安装了但服务器没装。另外要根据机器类型选择相应的jacob.dll文件(x86,x64),并将dll文件放在JDK安装目录下的\jre1.6.0_5\bin目录中,其实放在系统system32目录或tomcatbin目录下也可以,只要在java.library.path中就成。

 

import java.io.File;

 

import com.jacob.activeX.ActiveXComponent;

import com.jacob.com.ComThread;

import com.jacob.com.Dispatch;

import com.jacob.com.Variant;

 

public class JacobWord {

    private ActiveXComponent app;

    private Dispatch document;

    private Dispatch selection;

    private Dispatch paragraph;

    private Dispatch font;

 

    // 初始化并新建Word文档

    public JacobWord() {

       ComThread.InitSTA();// 初始化Com线程

       app = new ActiveXComponent("Word.Application");// 初始化word应用程序

       app.setProperty("Visible", new Variant(false));// 设置word文档不在前台打开

       app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏

       Dispatch docs = app.getProperty("Documents").toDispatch();// 获取文挡属性

       document = Dispatch.call(docs, "Add").toDispatch(); // 创建新文档

       selection = app.getProperty("Selection").toDispatch();// 获得选定内容

       paragraph = Dispatch.get(selection, "ParagraphFormat").getDispatch();// 段落

       font = Dispatch.get(selection, "Font").toDispatch();// 字体

    }

 

    public static void main(String[] args) {

       File filePath = new File("c:\\test");

       if (filePath.exists()) {

           new JacobWord().mergeWord(filePath.listFiles());

       }

    }

 

    // 合并Word文档

    private void mergeWord(File[] file) {

       try {

           setWordTitle();

           // 设置文本样式,不包括接下来要插入的WORD文档内容

           Dispatch.put(paragraph, "Alignment", "3");// 1: 2: 3:

           Dispatch.put(font, "Color", "1,0,0,0"); // 红色

           Dispatch.put(font, "Size", 12);

          

           for (int i = 0; i < file.length; i++) {

              String tempFile = file[i].getAbsolutePath();

              if (tempFile.endsWith(".doc") || tempFile.endsWith(".docx")) {

                  Dispatch.put(selection, "Text", file[i].getName() + "文档内容如下:");

                  Dispatch.call(selection, "MoveDown");

                  Dispatch.call(selection, "TypeParagraph"); // 空一行段落

                  Dispatch.call(selection, "insertFile", tempFile);// 插入文件内容

                  Dispatch.call(selection, "TypeParagraph"); // 空一行段落

              }

           }

 

           fillBookmarks(new String[] { "author" }, new String[] { "victor" });

           Dispatch.call(document, "SaveAs", new Variant("c:\\test\\test.doc")); //保存

           Dispatch.call(document, "Close", new Variant(false));// 关闭文档

       } catch (Exception ex) {

           ex.printStackTrace();

       } finally {

           app.invoke("Quit", new Variant(0));// 退出word应用

           ComThread.Release();// 释放Com线程

       }

    }

 

    // 设置合并后文档的标题及样式

    private void setWordTitle() {

       Dispatch.put(paragraph, "Alignment", 1);// 1: 2: 3:

       Dispatch.put(font, "Bold", new Variant(true));

       Dispatch.put(font, "Color", "0,0,0,0"); // 黑色

       Dispatch.put(font, "Size", 16);

       Dispatch.call(selection, "TypeText", "合并后的Word文档"); // 写入标题内容

       Dispatch.call(selection, "TypeParagraph"); // 空一行段落

    }

 

    // 填充书签

    private void fillBookmarks(String[] bookmarks, String[] fillValues) {

       Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();

       if (bookmarks.length == fillValues.length) {

           for (int i = 0; i < bookmarks.length; i++) {

              Variant isExist = Dispatch.call(bookMarks, "Exists", bookmarks[i]);

              if (isExist.getBoolean()) {

                  Dispatch item = Dispatch.call(bookMarks, "Item", bookmarks[i]).toDispatch();

                  Dispatch range = Dispatch.call(item, "Range").toDispatch();

                  Dispatch.put(range, "Text", fillValues[i]);

              }

           }

       }

    }

}

SpringBoot_Freemarker生成Word_多个表格+两层嵌套循环; 步骤说明: 1.用Microsoft Office Word打开word原件;将文档需要动态生成的内容,替换为属性名 ${name} 2.另存为,选择保存类型Word 2003 XML 文档(*.xml) 3.用Firstobject free XML editor打开文件,选择Tools下的Indent【或者按快捷键F8】格式化文件内容。左边是文档结构,右边是文档内容; 4. 文档生成后有时需要手动修改,查找第一步设置的属性名,可能会产生类似${n.....ame}类似的样子,我们将将名字间的标签删掉,恢复为${name} 5. word模板有表格,需要循环的位置, 用 标签将第二对 标签(即除表头的w:tr标签后的一对)包围起来 同时表格内的属性例如${name},在这里需要修改为${user.name} (userList是集合在dataMap的key, user是集合的每个元素, 类似), 如图: PLUS:若表格之外还有嵌套的循环,也需要用,注意这里的标签不要和某对其他标签交叉,不可以出现这种 6. 标识替换完之后,另存为.ftl后缀文件即可。 代码里是相对有一丢丢复杂的,两层嵌套循环; 总(dataMap) deptName 部门名 list(Table)表的集合 table1(map) table-名字 ${map.table} tableName-文名 ${map.tableName} columnCount-字段数 ${map.columnCount} recordCount-记录数 ${map.recordCount} listA-List--表格1 map.listA column Model属性——字段名 ${model.column} columnName Model属性——字段文名 ${model.column} rate Model属性——字段占比 ${model.rate} nullValueCount Model属性——字段空值数 ${model.nullValueCount} listB-List--表格2 map.listB …… listC-List--表格3 map.listC …… table2 table-名字 ${map.table} tableName-文名 ${map.tableName} columnCount-字段数 ${map.columnCount} recordCount-记录数 ${map.recordCount} listA-List--表格1 map.listA column Model属性——字段名 ${model.column} columnName Model属性——字段文名 ${model.column} rate Model属性——字段占比 ${model.rate} nullValueCount Model属性——字段空值数 ${model.nullValueCount} listB-List--表格2 map.listB …… listC-List--表格3 map.listC …… table3 ……
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值