美文网首页
freeMaker实现导出word功能(浏览器下载)

freeMaker实现导出word功能(浏览器下载)

作者: 寓含 | 来源:发表于2019-08-28 15:04 被阅读0次

1、介绍:freeMaker是一个模版引擎(https://freemarker.apache.org/

可以根据模版+数据-生成文件,多数是静态的,部分数据变更的情况

freeMarker

2、结合Spring使用freeMarker:

(0)模版数据的准备:

word中标记上需要替换的数据位置:例如-标记字样代替

然后将word另存为xml

在xml中替换掉做的标记入下:替换成${变量名}的形式

将生成的模版存放在:templateLoaderPath对应配置的目录

(1)配置pom:

    <groupId>org.freemarker

    <artifactId>freemarker

    <version>2.3.28

    <groupId>org.springframework

    <artifactId>spring-context-support

    <version>${spring-version}

</dependency>

注意:一定要应用spring-context-support,不然会报错

(2)添加Spring配置:

templateLoaderPath:是模版所在的目录

<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/ftl/"/> <property name="defaultEncoding" value="UTF-8"/> <property name="freemarkerSettings"> <!-- 设置默认的编码方式,原先是GBK,需要设置成utf-8 --> <props> <!--用于解决前端报空指针问题 不用再空值后面+ !号--> <prop key="classic_compatible">true</prop> <!-- <prop key="defaultEncoding">utf-8</prop> <prop key="template_exception_handler">rethrow</prop> --> </props> </property></bean>

nc

(3)java 代码:

@Autowired

private FreeMarkerConfigurerfreeMarkerConfigurer;

public Stringexport(int id,HttpServletResponse resp)throws IOException, TemplateException {

// 1、从spring容器中获得FreeMarkerConfigurer对象。

// 2、从FreeMarkerConfigurer对象中获得Configuration对象。

    Configuration configuration =freeMarkerConfigurer.getConfiguration();

    // 3、使用Configuration对象获得Template对象。

    Template template = configuration.getTemplate("产品需求规格说明书模板V1.5.2-for.xml");

    // 4、创建数据集

    Prd prd=proFileDao.getPrdById(id);

    System.out.println("export===="+prd.toString());

    Map prdModel= Maps.newHashMap();

    prdModel.put("title",prd.getTitle());

    SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");

  prdModel.put("time",sdf.format(prd.getCreateTime()));

    prdModel.put("createUser",prd.getCreateUser());

    prdModel.put("oneText",prd.getOneText());

    prdModel.put("twoTextOne",prd.getTwoTextOne());

    prdModel.put("twoTextTwo",prd.getTwoTextTwo());

    //浏览器下载

    resp.setContentType("application/vnd.ms-excel");

    resp.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(prd.getTitle(), "UTF-8") +".doc");

    // 5、创建输出文件的Writer对象。

    Writer out = out =new BufferedWriter(new OutputStreamWriter(resp.getOutputStream()));

    // 6、调用模板对象的process方法,生成文件。

    template.process(prdModel, out);

    // 7、关闭流。

    out.close();

    return "OK";

}

相关文章

网友评论

      本文标题:freeMaker实现导出word功能(浏览器下载)

      本文链接:https://www.haomeiwen.com/subject/manpectx.html