java通过模板导出word

前言

最近在整理之前在工作中遇到的一些问题,之前在做项目的时候需要根据模板导出word,在写完导出之后写下这篇博客。


一、所用的依赖

我在做导出excel的时候用到了POI这个依赖,下边为依赖坐标.

		<dependency>
			<groupId>com.deepoove</groupId>
			<artifactId>poi-tl</artifactId>
			<version>1.3.0</version>
		</dependency>

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>3.17</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.7</version>
		</dependency>

二、用到的API

map.put("picture1", new PictureRenderData(520, 300, picture));//插入图片
//插入各种文字段落 
map.put("info",new TextRenderData("111111","文档内容1"));
map.put("date","2021-04-03");

模板样式在这里插入图片描述

二、代码如下

代码如下(示例):

    public String getWordByDate(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        try {
            	//日期
            	Date date=new Date();
            	String start = sdf.format(date);
            
            	//模板路径
            	String templ = "D://temple//WordTemple.docx";
            	//图片路径
           	 	String wordPath  = "D://image";
            
            	Map<String, Object> map= new HashMap<String, Object>();
           		map.put("picture1", new PictureRenderData(520, 300, picture));//插入图片
				//插入各种文字段落 
				map.put("info",new TextRenderData("111111","文档内容1"));
				map.put("date","2021-04-03");
                //将生成的文件保存到指定目录下
                String filePath ="D://file";
                XWPFTemplate template = XWPFTemplate.create(templ);
                RenderAPI.render(template, datas);
                Date day=new Date();    
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 
                  //输出文件
                result =df.format(day)+".docx";
                File outFile = new File(filePath+"/"+result);
                //如果输出目标文件夹不存在,则创建
                if (!outFile.getParentFile().exists()){
                    outFile.getParentFile().mkdirs();
                }
                FileOutputStream out = new FileOutputStream(outFile);
                template.write(out);
                out.flush();
                out.close();
                template.close();
        }finally {   
        }
    }

总结

上面就是导出word用到的方法,注意:word模板必须是.docx文件!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值