jacob 使用模板导出word

2024-02-17 07:08
文章标签 模板 使用 导出 word jacob

本文主要是介绍jacob 使用模板导出word,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

/*************************************
 *
 *作用:利用jacob插件根据模板word生成word 文件!
 *
 *传入数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表用来替换的值。
 * word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾,如:$code$、$date$……,以免执行错误的替换。
 * 所有要替换为图片的字段,Key中需包含image或者Value为图片的全路径(目前只判断文件后缀名为:.bmp、.jpg、.gif)。
 * 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:R代表从表格的第R行开始替换,N代表word模板中的第N张表格;
 * Value为ArrayList对象,ArrayList中包含的对象统一为String[],一条String[]代表一行数据,ArrayList中第一条记录为特殊记录,
 * 记录的是表格中要替换的列号,如:要替换第一列、第三列、第五列的数据,则第一条记录为String[3] {“1”,”3”,”5”}。
 *
 *
 *create on 2007.3.6
 *author fgl
 *
 *
 ************************************/

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class Java2Word {
    private boolean saveOnExit;
    /**
     * word文档
     */
    private Dispatch doc = null;
    /**
     * word运行程序对象
     */
    private ActiveXComponent word;
    /**
     * 所有word文档
     */
    private Dispatch documents;

    /**
     * 构造函数
     */
    public Java2Word() {
        saveOnExit = false;
        word = new ActiveXComponent("Word.Application");
        word.setProperty("Visible", new Variant(false));
        documents = word.getProperty("Documents").toDispatch();
    }

    /**
     * 设置参数:退出时是否保存
     *
     * @param saveOnExit
     *            true-退出时保存文件,false-退出时不保存文件
     */
    public void setSaveOnExit(boolean saveOnExit) {
        this.saveOnExit = saveOnExit;
    }

    /**
     * 得到参数:退出时是否保存
     *
     * @return boolean true-退出时保存文件,false-退出时不保存文件
     */
    public boolean getSaveOnExit() {
        return saveOnExit;
    }

    /**
     * 打开文件
     *
     * @param inputDoc
     *            要打开的文件,全路径
     * @return Dispatch 打开的文件
     */
    public Dispatch open(String inputDoc) {
        return Dispatch.call(documents, "Open", inputDoc).toDispatch();
    }

    /**
     * 选定内容
     *
     * @return Dispatch 选定的范围或插入点
     */
    public Dispatch select() {
        return word.getProperty("Selection").toDispatch();
    }

    /**
     * 把选定内容或插入点向上移动
     *
     * @param selection
     *            要移动的内容
     * @param count
     *            移动的距离
     */
    public void moveUp(Dispatch selection, int count) {
        for (int i = 0; i < count; i++)
            Dispatch.call(selection, "MoveUp");
    }

    /**
     * 把选定内容或插入点向下移动
     *
     * @param selection
     *            要移动的内容
     * @param count
     *            移动的距离
     */
    public void moveDown(Dispatch selection, int count) {
        for (int i = 0; i < count; i++)
            Dispatch.call(selection, "MoveDown");
    }

    /**
     * 把选定内容或插入点向左移动
     *
     * @param selection
     *            要移动的内容
     * @param count
     *            移动的距离
     */
    public void moveLeft(Dispatch selection, int count) {
        for (int i = 0; i < count; i++)
            Dispatch.call(selection, "MoveLeft");
    }

    /**
     * 把选定内容或插入点向右移动
     *
     * @param selection
     *            要移动的内容
     * @param count
     *            移动的距离
     */
    public void moveRight(Dispatch selection, int count) {
        for (int i = 0; i < count; i++)
            Dispatch.call(selection, "MoveRight");
    }

    /**
     * 把插入点移动到文件首位置
     *
     * @param selection
     *            插入点
     */
    public void moveStart(Dispatch selection) {
        Dispatch.call(selection, "HomeKey", new Variant(6));
    }

    /**
     * 从选定内容或插入点开始查找文本
     *
     * @param selection
     *            选定内容
     * @param toFindText
     *            要查找的文本
     * @return boolean true-查找到并选中该文本,false-未查找到文本
     */
    public boolean find(Dispatch selection, String toFindText) {
        // 从selection所在位置开始查询
        Dispatch find = Dispatch.call(selection, "Find").toDispatch();
        // 设置要查找的内容
        Dispatch.put(find, "Text", toFindText);
        // 向前查找
        Dispatch.put(find, "Forward", "True");
        // 设置格式
        Dispatch.put(find, "Format", "True");
        // 大小写匹配
        Dispatch.put(find, "MatchCase", "True");
        // 全字匹配
        Dispatch.put(find, "MatchWholeWord", "True");
        // 查找并选中
        return Dispatch.call(find, "Execute").getBoolean();
    }

    /**
     * 把选定内容替换为设定文本
     *
     * @param selection
     *            选定内容
     * @param newText
     *            替换为文本
     */
    public void replace(Dispatch selection, String newText) {
        // 设置替换文本
        Dispatch.put(selection, "Text", newText);
    }

    /**
     * 全局替换
     *
     * @param selection
     *            选定内容或起始插入点
     * @param oldText
     *            要替换的文本
     * @param newText
     *            替换为文本
     */
    public void replaceAll(Dispatch selection, String oldText, Object replaceObj) {
        // 移动到文件开头
        moveStart(selection);
        if (oldText.startsWith("table") || replaceObj instanceof List) {
            replaceTable(selection, oldText, (List) replaceObj);
        } else {
            String newText = (String) replaceObj;
            if (oldText.indexOf("image") != -1
                    || newText.lastIndexOf(".bmp") != -1
                    || newText.lastIndexOf(".jpg") != -1
                    || newText.lastIndexOf(".gif") != -1)
                while (find(selection, oldText)) {
                    replaceImage(selection, newText);
                    Dispatch.call(selection, "MoveRight");
                }
            else
                while (find(selection, oldText)) {
                    replace(selection, newText);
                    Dispatch.call(selection, "MoveRight");
                }
        }
    }

    /**
     * 替换图片
     *
     * @param selection
     *            图片的插入点
     * @param imagePath
     *            图片文件(全路径)
     */
    public void replaceImage(Dispatch selection, String imagePath) {
        Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
                "AddPicture", imagePath);
    }

    /**
     * 替换表格
     *
     * @param selection
     *            插入点
     * @param tableName
     *            表格名称,形如table$1@1、table$2@1...table$R@N,R代表从表格中的第N行开始填充,
     *            N代表word文件中的第N张表
     * @param fields
     *            表格中要替换的字段与数据的对应表
     */
    public void replaceTable(Dispatch selection, String tableName, List dataList) {
        if (dataList.size() <= 1) {
            System.out.println("Empty table!");
            return;
        }
        // 要填充的列
        String[] cols = (String[]) dataList.get(0);
        // 表格序号
        String tbIndex = tableName.substring(tableName.lastIndexOf("@") + 1);
        // 从第几行开始填充
        int fromRow = Integer.parseInt(tableName.substring(
                tableName.lastIndexOf("$") + 1, tableName.lastIndexOf("@")));
        // 所有表格
        Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
        // 要填充的表格
        Dispatch table = Dispatch.call(tables, "Item", new Variant(tbIndex))
                .toDispatch();
        // 表格的所有行
        Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
        // 填充表格
        for (int i = 1; i < dataList.size(); i++) {
            // 某一行数据
            String[] datas = (String[]) dataList.get(i);
            // 在表格中添加一行
            if (Dispatch.get(rows, "Count").getInt() < fromRow + i - 1)
                Dispatch.call(rows, "Add");
            // 填充该行的相关列
            for (int j = 0; j < datas.length; j++) {
                // 得到单元格
                Dispatch cell = Dispatch.call(table, "Cell",
                        Integer.toString(fromRow + i - 1), cols[j])
                        .toDispatch();
                // 选中单元格
                Dispatch.call(cell, "Select");
                // 设置格式
                Dispatch font = Dispatch.get(selection, "Font").toDispatch();
                Dispatch.put(font, "Bold", "0");
                Dispatch.put(font, "Italic", "0");
                // 输入数据
                Dispatch.put(selection, "Text", datas[j]);
            }
        }
    }

    /**
     * 保存文件
     *
     * @param outputPath
     *            输出文件(包含路径)
     */
    public void save(String outputPath) {
        Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),
                "FileSaveAs", outputPath);
    }

    /**
     * 关闭文件
     *
     * @param document
     *            要关闭的文件
     */
    public void close(Dispatch doc) {
        Dispatch.call(doc, "Close", new Variant(saveOnExit));
    }

    /**
     * 退出程序
     */
    public void quit() {
        word.invoke("Quit", new Variant[0]);
        ComThread.Release();
    }

    /**
     * 根据模板、数据生成word文件
     *
     * @param inputPath
     *            模板文件(包含路径)
     * @param outPath
     *            输出文件(包含路径)
     * @param data
     *            数据包(包含要填充的字段、对应的数据)
     */
    public void toWord(String inputPath, String outPath, HashMap data) {
        String oldText;
        Object newValue;
        try {
            doc = open(inputPath);
            Dispatch selection = select();
            Iterator keys = data.keySet().iterator();
            while (keys.hasNext()) {
                oldText = (String) keys.next();
                newValue = data.get(oldText);
                replaceAll(selection, oldText, newValue);
            }
            save(outPath);
        } catch (Exception e) {
            System.out.println("操作word文件失败!"+e.getMessage());
        } finally {
            if (doc != null)
                close(doc);
        }
    }
    
    
    
    public static void main(String[] args) {
        Java2Word java2word  = new Java2Word();
        HashMap<String, String> data = new HashMap<String,String>();
        
        data.put("$VAR$", "君不见黄河之水天上来");
        
        java2word.toWord("F:\\template.doc", "F:\\result.doc", data);
        
    }
}

这篇关于jacob 使用模板导出word的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/717032

相关文章

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

oracle DBMS_SQL.PARSE的使用方法和示例

《oracleDBMS_SQL.PARSE的使用方法和示例》DBMS_SQL是Oracle数据库中的一个强大包,用于动态构建和执行SQL语句,DBMS_SQL.PARSE过程解析SQL语句或PL/S... 目录语法示例注意事项DBMS_SQL 是 oracle 数据库中的一个强大包,它允许动态地构建和执行

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

Python itertools中accumulate函数用法及使用运用详细讲解

《Pythonitertools中accumulate函数用法及使用运用详细讲解》:本文主要介绍Python的itertools库中的accumulate函数,该函数可以计算累积和或通过指定函数... 目录1.1前言:1.2定义:1.3衍生用法:1.3Leetcode的实际运用:总结 1.1前言:本文将详