一、依赖jar包
1、spring-webmvc-2.5.6.jar
2、rtftemplate-1.0.1-b13.jar
二、制作模板
1、新建一个word,另存为rtf格式
2、用word打开rtf,另存为html格式
3、复制html代码到工程里的页面文件(.jsp,.html,.ftl)中
三、java(Action)类代码
//action接口注入
private FreeMarkerConfigurer freeMarkerConfigurer;
public static String LoadFile(String strFileName){
StringBuffer sb = new StringBuffer();
try {
BufferedReader fieldbuff = new BufferedReader(new InputStreamReader(
new FileInputStream(strFileName),"utf-8"));
String fieldline = "";
while ((fieldline = fieldbuff.readLine()) != null) {
sb.append(fieldline);
}
fieldbuff.close();
// ffield.close();
} catch (IOException e) {
System.out.println("this file not exist(没有找到)" + strFileName);
}
return sb.toString();
}
public String printWord() throws Exception{
try {
//相对路径
String path = this.getRequest().getScheme()+":"+ this.getRequest().getServerName()+":"+ this.getRequest().getServerPort() + this.getRequest().getContextPath();
//绝对路径
path = ServletActionContext.getServletContext().getRealPath( "/template/word/book_qzcs_jueding.ftl" );
String template = LoadFile(path);
entityM = (BookQzcsJuedingM)this.getFacade().findById(getEntityM());
Map<String, Object> contextMap = new HashMap<String, Object>();
contextMap.put("entity", entityM);//对应ftl标签名称
//freeMarker 解析开始
Configuration configuration = freeMarkerConfigurer.getConfiguration();
StringTemplateLoader strLoader = new StringTemplateLoader();
strLoader.putTemplate("template", template);
configuration.setTemplateLoader(strLoader);
Template t=configuration.getTemplate("template");
filestr = FreeMarkerTemplateUtils.processTemplateIntoString(t, contextMap);
fileName = new String(("生成文件的名称").getBytes(),"ISO8859-1");
return "download";
} catch (Exception e) {
e.printStackTrace();
}
return ERROR;
}
// 输出方法
public InputStream getInputStream() throws FileNotFoundException, UnsupportedEncodingException {
return new ByteArrayInputStream(filestr.getBytes("utf-8"));
}
四、Struts.xml位置文件配置
<action name="name*" class="com.*****.Action" method="{1}">
<result type="stream" name="download">
<param name="contentType">application/octet-stream;charset=utf-8</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>
五、spring.xml位置文件配置
<!-- 生成words调用的接口配置 -->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">utf-8</prop>
<prop key="locale">no_NO</prop>
<prop key="template_update_delay">5</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="number_format">#</prop>
</props>
</property>
</bean>