根据数据及模板生成word文档

maven依赖:

<!-- 支持Word文档的操作 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.13</version>
</dependency>

<!-- freemarker -->
  <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<!-- 找不到,还必须有这个依赖 -->
<dependency>
      <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.20</version>

</dependency>

生成一个word模板,需要动态生成的数据用占位符代替,例如:

姓    名

${name}

性   别

${sex}

然后把模板保存为xml格式,打开生成的xml文件找到<w:t>${name}</w:t>改为<w:t>${name?if_exists}</w:t>

后台java部分

public class WordPoi {
public static void main(String[] args) throws IOException, TemplateException {
Map<String, Object> map = new HashMap<String, Object>(); 
        map.put("name", "张三");  
      map.put("age", 18);
        setWord(map,"生成word文件名称");
}    
    public static void setWord(Map<String, Object> map,String name) throws TemplateException, IOException {
            //获取当前系统桌面路径
            String path = CurrentUserTool.path();
            //模板的路径  
            File fir = new File("D:/");
            //生成文件的路径及文件名。默认桌面  
            File outFile = new File(path+"/"+name+".doc");  
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));  
            // 使用FileTemplateLoader  
            //指定模板路径  
            TemplateLoader templateLoader = new FileTemplateLoader(fir);
            String tempname = "基本信息表.xml"; 
            Configuration cfg = new Configuration();  
            cfg.setTemplateLoader(templateLoader);  
            Template t = cfg.getTemplate(tempname, "UTF-8");  
              
            t.process(map, out);
            out.flush();  
            out.close();  
            System.out.println("解析成功!");  
    }   
}

运行后,桌面就会生成"张三.doc"文件了


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值