效果展示:

         使用word编辑好模板

 Java使用velocity导出word

先在模板中填充部分数据(之所以先写好两条数据,是为了在保存为xml用文本编辑器打开后快速定位到需要出传入的数据。增加不同颜色的两条数据,是为了判断颜色),然后保存文件为Java使用velocity导出word

然后再用普通的文本编辑器打开

 Java使用velocity导出word

以上是模板的创建。

         导出后的word文档展示

 Java使用velocity导出word

 

开发过程记录:

1,  首先创建工程,导入Java使用velocity导出word

2,  创建模板文件,Java使用velocity导出word将修改好的xml文件用普通文本工作打开,然后复制到改文件中。

3,  新建Java使用velocity导出word

4,  执行该类,即可导出word。

代码展示:

 

Person.java

 

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStreamWriter;

import java.util.ArrayList;

import java.util.List;

import java.util.Properties;

 

import org.apache.velocity.Template;

import org.apache.velocity.VelocityContext;

import org.apache.velocity.app.VelocityEngine;

 

public class VelocityUtils {

 

  public static void createDoc(VelocityContext vc, String templetePath) throws Exception {

    Properties ps = new Properties();

    ps.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "./src/");// 这是模板所在路径

    VelocityEngine ve = new VelocityEngine();

    ve.init(ps);

    ve.init();

    Template template = ve.getTemplate(templetePath, "utf-8");

 

    File srcFile = new File("C:/Users/Administrator/Desktop/abc.doc");//输出路径

    FileOutputStream fos = new FileOutputStream(srcFile);

    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));

    template.merge(vc, writer);

    writer.flush();

    writer.close();

    fos.close();

  }

 

  public static void main(String[] args) {

    VelocityContext velocityContext = new VelocityContext();

    velocityContext.put("title", "测试");

    List<Person> personMap=new ArrayList<Person>();

    for(int i=0;i<5;i++){

             Person p=new Person();

             p.setId("0000"+String.valueOf(0+i));

             p.setName("liuhanchang"+i);

             p.setSex("男");

             p.setAge(22);

             personMap.add(p);

    }

    velocityContext.put("personMap",personMap);

    try {

      VelocityUtils.createDoc(velocityContext, "velocityMes.vm");

      System.out.println("=====");

    } catch (Exception e) {

      e.printStackTrace();

    }

  }

}
View Code

相关文章:

  • 2021-08-10
  • 2022-03-07
  • 2021-12-18
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2021-09-04
猜你喜欢
  • 2022-12-23
  • 2021-12-05
  • 2021-05-11
  • 2021-08-26
  • 2021-05-01
  • 2022-02-24
  • 2021-12-06
相关资源
相似解决方案