asposeword实现doc模板操作-实例总结

项目中用到了根据模板生成word文件的功能,需要根据模板填充数据,这里介绍一下使用到的asposeword的学习总结

一下根据实际开发展示如何应用

准备工作

项目使用spring boot进行maven依赖集成

jar包网盘提取:

链接:https://pan.baidu.com/s/1Vd_lZkfKh9Wt0Zk8urFqTQ 
提取码:57vx

<!-- 报表依赖 -->
<dependency>
    <groupId>com.aspose-words</groupId>
    <artifactId>aspose-words</artifactId>
    <version>16.8.0</version>
</dependency>

resources下配置认证文件license.xml:

<License>
  <Data>
    <Products>
      <Product>Aspose.Total for Java</Product>
      <Product>Aspose.Words for Java</Product>
    </Products>
    <EditionType>Enterprise</EditionType>
    <SubscriptionExpiry>20991231</SubscriptionExpiry>
    <LicenseExpiry>20991231</LicenseExpiry>
    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
  </Data>
  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

解决jar包由于maven仓库中没有源导致无法下载,需要手动添加问题:

1. 将依赖的jar包放置在本地磁盘中

2. 确认配置有maven环境并配置有本地仓库,打开cmd

3. 执行以下命令(示例中jar包放置在F:盘符下)

mvn install:install-file -Dfile=F:\aspose-words-16.8.0-jdk16.jar -DgroupId=com.aspose-words -DartifactId=aspose-words -Dversion=16.8.0 -Dpackaging=jar 

-Dfile的后面输入的为你下载的第三方jar包的本地文件路径

-DgroupId的后面输入的为你转maven jar包后groupId的标签内容<groupId>QRCode</groupId>。

-DartifactId的后面输入的为你转maven jar包后artifactId的标签内<artifactId>QRCode</artifactId>

-Dversion的后面输入的为你转maven jar包后version的标签内容版本号<version>3.0</version>

4. 确认jar导入到本地仓库,在项目中pom中添加依赖,根据上述的groupid等信息

工具类

AsposeWordUtil 

public class AsposeWordUtil {
	
	private Document doc;
	private DocumentBuilder builder; 
	private InputStream doctemplate;
	/**
	 * 根据模板文件创建对象
	 * @param tempfilepath 模板文件路径
	 * @throws Exception
	 */
	public AsposeWordUtil(String tempfilepath) throws Exception{
//		ClassLoader loader = Thread.currentThread().getContextClassLoader();
//		String path = loader.getResource("asposeword/license.xml").getPath();
//		if(path.startsWith("/")){
//			path = path.substring(1);
//		}
//		//Linux 环境下添加此标识,Windows环境下删除此标识
//		path = "/"+path;
//		InputStream license = new FileInputStream(path);
		//以下为认证文件license的存放位置
		String fileName = "classpath:/asposeword/license.xml";
		ResourceLoader resourceLoader = new DefaultResourceLoader();
		Resource res = resourceLoader.getResource(fileName);
		InputStream license = res.getInputStream();
		License aposeLic = new License();
        aposeLic.setLicense(license);
        
        
        doctemplate = resourceLoader.getResource(tempfilepath).getInputStream();
        
		doc = new Document(doctemplate);
		builder = new DocumentBuilder(doc);
	}
	/**
	 * 插入书签
	 * @param locationkey在某个书签后插入
	 * @param key书签名
	 * @param isnewline是否换行
	 * @throws Exception
	 */
	public void setBookmark(String locationkey,String key,boolean isnewline) throws Exception{
		builder.moveToBookmark(locationkey);
		if(isnewline) builder.writeln();
		builder.startBookmark(key);
//	    builder.writeln(key);
		builder.endBookmark(key);
	}
	/**
	 * 动态生成书签
	 * @param key
	 * @throws Exception
	 */
	public void setBookmark(String key) throws Exception{  
		builder.writeln();
		builder.startBookmark(key);
//	    builder.writeln(key);
		builder.endBookmark(key);
	}
	/**
	 * 书签填入内容
	 * @param key    书签名称
	 * @param value  填入值
	 * @throws Exception
	 */
	public void setBookmarksValue(String key,String value) throws Exception{
		doc.getRange().getBookmarks().get(key).setText(value);
	}
	
	/**
	 * 多个书签填入内容
	 * @param kvs  书签名称和填入值map
	 * @throws Exception 
	 */
	public void setBookmarksValue(Map<String,String> kvs) throws Exception{
		for(Map.Entry<String, String> entity:kvs.entrySet()){
			setBookmarksValue(entity.getKey(),entity.getValue());
		}
	} 
	/**
	 * 插入另一个文档的内容
	 * @param key   书签位置
	 * @param out   图片流
	 * @throws Exception
	 */
	public void setBookmarkDocument(String key,String filename) throws Exception{
		Document doc1=new Document(ReportTemplate.getInstance().getReportTemplate(filename));
		builder.moveToBookmark(key);
		builder.insertDocument(doc1, ImportFormatMode.KEEP_DIFFERENT_STYLES);
	}
	/**
	 * 插入图片
	 * @param key         书签位置
	 * @param filePath    图片文件路径
	 * @throws Exception
	 */
	public void setBookmarkImage(String key,String filePath) throws Exception{
		builder.moveToBookmark(key);
		builder.insertImage(filePath);
	}
	
	/**
	 * 插入图片
	 * @param key   书签位置
	 * @param out   图片流
	 * @throws Exception
	 */
	public void setBookmarkImage(String key,ByteArrayOutputStream out) throws Exception{
		ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
        ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
		builder.moveToBookmark(key);
		builder.insertImage(swapStream);
	}
	
	/**
	 * 表格增加行
	 * @throws Exception 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void table(List<ParagraphBean> pblist) throws Exception{
		NodeCollection allTables = doc.getChildNodes(NodeType.TABLE, true);  //获取模板中的所有表格
		Table table = (Table)allTables.get(0);                               //取到第一个表格
		// 创建行
		Row r = new Row(doc);
		Cell c = new Cell(doc);		
		for(ParagraphBean pb:pblist){
			if(pb.getType()==1){
				//文本
				Paragraph p = new Paragraph(doc);
				Run run = new Run(doc,pb.getData().toString());
				run.getFont().setSize(14);
				p.appendChild(run);
				if(pb.getAlignment()!=-1){
					p.getParagraphFormat().setAlignment(pb.getAlignment());
				}
				c.appendChild(p);
			}else if(pb.getType()==2){
				Paragraph p = new Paragraph(doc);
				//图片
				List<ByteArrayOutputStream> baos = (List<ByteArrayOutputStream>)pb.getData();
				for(ByteArrayOutputStream bao:baos){
					ByteArrayInputStream swapStream = new ByteArrayInputStream(bao.toByteArray());
					/*
					Shape shape=new Shape(doc,ShapeType.IMAGE);					
					shape.getImageData().setImage(swapStream);
					//shape.setHeight(200);
					*/
					Shape shape = builder.insertImage(swapStream);					
					p.appendChild(shape);
				}
				c.appendChild(p);
			}
		}
		r.getCells().add(c);
		table.getRows().add(r);
	}
	
	/**
	 * 保存到内存流中
	 * @return
	 * @throws Exception
	 */
	public ByteArrayOutputStream save() throws Exception{		
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		doc.save(outputStream, SaveFormat.DOC);
		return outputStream;
	}

}

ParagraphBean 

public class ParagraphBean {
	private int type;       // 类型【1:文本,2:图片】
	private int alignment;  // 对齐方式
	private Object data;    // 数据
	
	/**
	 * 初始化段
	 * @param type  类型【1:文本,2:图片】
	 * @param data  数据
	 */
	public ParagraphBean(int type,Object data){
		this.type=type;
		this.data=data;
		this.alignment=-1;
	}
	
	public ParagraphBean(int type,int alignment,Object data){
		this.type=type;
		this.alignment=alignment;
		this.data=data;
	}
	
	/**
	 * 获取数据类型
	 * @return  类型【1:文本,2:图片】
	 */
	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getAlignment() {
		return alignment;
	}
	public void setAlignment(int alignment) {
		this.alignment = alignment;
	}
	
	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}
	
}

 

public class ReportFileCreate {

	private static ReportFileCreate reportFileCreate; 
	
	public void init() {
		reportFileCreate = this;
	}

	public static ReportFileCreate getInstance() {
		return new ReportFileCreate();
	}

	public static AsposeWordUtil aspose;
	
	/**
	 * 	生成文件
	 * @throws Exception 
	 */
	public String createDoc(Map<String, String> params) throws Exception {
		aspose = new AsposeWordUtil("classpath:/asposeword/template/reply.dotx");
		aspose.setBookmarksValue(params);
        //DateUtil.getSdfTimesSS()获取的是当前年月日时分秒的时间戳,20200501100155
		String fileName = DateUtil.getSdfTimesSS() + ".doc"; 
		boolean flag = aspose.save(fileName);
		if(flag) {
			return fileName;
		} else {
			return "";
		}
	}

}

 

开发应用

首先,创建word模板,这里仅展示比较简单的模板应用

插入书签:name,age在各自的表格位置中 ,保存模板并将模板放置在项目resources/asposeword/temp下

生成文件下载

	public void createFh(Map<String, Object> map) {
		Map<String, String> params = new HashMap<String, String>();
                params.put("name", "张三");
		params.put("age", 18);
		try {
			fileName = ReportFileCreate.getInstance().createDoc(params);
            /**
             * 以下方式可以获取到内存流中生成的文件,因博主实际应用中是将文件存储到了ftp中,
             * 非直接下载下来,所以各位根据示例需求完成下载操作吧
             */
                    File file = new File(fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

如有问题可以咨询,写的不周到还请包涵

不积跬步无以至千里,不积小流无以成江海;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章