java使用Aspose.word向word模板填充数据

本文详细介绍如何使用Aspose库在Java环境下实现Word文档模板的自动化填充,包括文本、图片及表格数据的替换,以及如何避免水印和提高转换效率。
该文章已生成可运行项目,

1.word模板制作

  1. 在word文档光标位置,插入 -》文档部件 -》域,弹框如下:

最终生成的模板文档如下:

注:图片域和单个变量域是同一个,定义图片域时,同一个图片需要定义不同的域名。

2.工具类准备

  1. 使用Aspose进行文档转换,首先引入相应的jar包到系统环境
  2. 项目resource下导入license.xml文件
  3. 使用Aspose时,需要调用设置License方法,设置完成第一次替换比较慢,再次就不需要设置License方法,效率会更高。

注意:使用Aspose时,每一个模块(words,pdf,cells)都有相同的类,如License类,SaveOptions类,SaveFormat类,功能各不相同。

获取license示例代码:

package com.sinoif.common.utils;

import com.aspose.words.License;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

/**
 * @description:
 * @author: guanlj
 * @date: 2020/7/24 11:10
 */
@Slf4j
public class AsposeLicenseUtil {
	private static License aposeLic = new License();

	/**
	 * 获取License的输入流
	 *
	 * @return
	 */
	private static InputStream getLicenseInput() {

		InputStream inputStream = null;
		ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
		try {
            //获取项目resource下的文件流
			inputStream = contextClassLoader.getResourceAsStream("license.xml");
		} catch (Exception e) {
			log.error("license not found!"+ e);
		}
		return inputStream;
	}

	/**
	 * 设置License
	 *
	 * @return true表示已成功设置License, false表示失败
	 */
	public static boolean setWordsLicense() {
		if (!aposeLic.getIsLicensed()) {
			try {
				aposeLic.setLicense(getLicenseInput());
				return aposeLic.getIsLicensed();
			} catch (Exception e) {
				log.error("set words license error!", e);
			}
		}
		return aposeLic.getIsLicensed();
	}

}

 

3.模板填充

代码示例:

package com.sinoif.common.utils;

import com.aspose.words.*;
im
本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值