[关闭]
@HUST-SuWB 2015-01-30T08:51:41.000000Z 字数 8662 阅读 404

SSH框架下的Word下载

项目实战


最近在做SSH框架下的Word文档下载,也就是导出的功能。参考了很多的资料,从POI到iText再到freemarker,poi更适合操作excel,从易用性考虑,我一开始选择了freemarker,而实际应用中,碰到了很多问题,因此记录下。
首先是freemarker的用法,有个参考资料很好用。http://www.havenliu.com/java/514.html 这里介绍得很详细,我简单说一下,基本的步骤就是
1、原始模板文档在2003版office中另存为xml文件
2、编辑此xml文件,将其中所有待插值的部分标记好(这里推荐的xml编辑软件是firstObject)
3、直接修改已经标记好后的.xml文件为.ftl文件,这就是待用的模板
4、程序调用模板,写入Map数据,生成文档
这个流程走下来,一般都不会有问题。

一、freemarker操作模板文件写入文档数据

下面附上这种方式的代码
struts的配置就是很普通的那种,

  1. <action name="test" class="testAction" method="test">
  2. <result type="json"><param name="root">jsonMap</param></result>
  3. </action>

然后是action层

  1. //word导出
  2. public String toWord() throws IOException{
  3. WordExport we = null;
  4. Applicant app = dao.query(Applicant.class, appId);
  5. if(fileType==1){
  6. fileFileName = "D:\\中心(助理研究员)岗位申请书.doc";
  7. json.put("name", app.getName()!=null?app.getName():"");
  8. json.put("gender", app.getGender()!=null?app.getGender():"");
  9. json.put("department", app.getDepartment()!=null?app.getDepartment():"");
  10. json.put("major", app.getMajor()!=null?app.getMajor():"");
  11. json.put("startDate", app.getStartDate()!=null?app.getStartDate():"");
  12. json.put("graduateDate", app.getGraduateDate()!=null?app.getGraduateDate():"");
  13. json.put("email", app.getEmail()!=null?app.getEmail():"");
  14. json.put("qq", app.getQq()!=null?app.getQq():"");
  15. json.put("introducation", app.getIntroduction()!=null?app.getIntroduction():"");
  16. json.put("studentType", app.getStudentType()!=null?app.getStudentType():"");
  17. json.put("teacher", app.getTeacher()!=null?app.getTeacher():"");
  18. json.put("phone", app.getMobilePhone()!=null?app.getMobilePhone():"");
  19. json.put("address", app.getAddress()!=null?app.getAddress():"");
  20. we = new WordExport(json, "applyWord.ftl", fileFileName);
  21. }else if(fileType ==2){
  22. fileFileName = "D:\\聘用协议书.doc";
  23. json.put("name", app.getName()!=null?app.getName():"");
  24. json.put("phone", app.getMobilePhone()!=null?app.getMobilePhone():"");
  25. json.put("address", app.getAddress()!=null?app.getAddress():"");
  26. we = new WordExport(json, "agreementWord.ftl", fileFileName);
  27. }
  28. we.createWord();
  29. return SUCCESS;
  30. }

再来是底层的wordExport类

  1. package csdc.tool;
  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.OutputStreamWriter;
  8. import java.io.Writer;
  9. import java.util.Map;
  10. import freemarker.template.Configuration;
  11. import freemarker.template.Template;
  12. import freemarker.template.TemplateException;
  13. /**
  14. * 指定模板导出word文档
  15. * @author suwb
  16. *
  17. */
  18. /**
  19. * 1、将模板word文档(2003版)另存为xml文件
  20. * 2、用firstObject打开xml文件,使用freeMarker标记(${标记})编辑其中待填入数据的地方
  21. * 3、将该模板置于指定目录下待程序读取
  22. * 4、确定待填入的数据和输出路径,调用程序执行
  23. */
  24. public class WordExport {
  25. private Configuration configuration = null;
  26. private Map<String,Object> dataMap;//待填充数据
  27. private String targetDir;//输出文件路径
  28. private String fileName;//模板文件名
  29. public WordExport(Map<String,Object> map, String file, String target){
  30. configuration = new Configuration();
  31. configuration.setDefaultEncoding("UTF-8");
  32. dataMap = map;
  33. targetDir = target;
  34. fileName = file;
  35. }
  36. public void createWord() throws IOException{
  37. Template t=null;
  38. //FTL文件所存在的位置
  39. configuration.setClassForTemplateLoading(getClass(), "/csdc/tool/templates");
  40. try {
  41. t = configuration.getTemplate(fileName); //文件名
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. File outFile = new File(targetDir);
  46. Writer out = null;
  47. try {
  48. out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
  49. } catch (FileNotFoundException e1) {
  50. e1.printStackTrace();
  51. }
  52. try {
  53. t.process(dataMap, out);
  54. } catch (TemplateException e) {
  55. e.printStackTrace();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. } finally{
  59. out.close();
  60. }
  61. }
  62. }

二、集成struts

上述方式可以实现在固定路径下的文件输出,但是我的需求是希望用户在页面上点击以后浏览器弹框出来供用户选择下载路径等,而上述方式只能在固定路径下生成文件,而且文件生成过程在用户界面上不可见,也就是说,这种方式与struts2的下载方式没有任何关系,struts2的下载是在配置文件里配置好

  1. <result name="success" type="stream">
  2. <param name="contentType">application/vnd.ms-word</param>
  3. <param name="contentDisposition">attachment;filename="${filename}"</param>
  4. <param name="inputName">downloadFile</param>
  5. </result>

通过这种配置,并在get+"inputName"这种方式命名的方法里返回一个inputStream类型的流,浏览器就会自动识别这是个文档下载,会弹出下载框。而freemarker的流程中,我始终得不到正常的inputStream流。
为了与struts2的下载功能相结合,我首先把程序改成了如下(当然,struts2的配置如上所述)

  1. /**
  2. * 导出word
  3. * @return
  4. */
  5. public String excute(){
  6. return SUCCESS;
  7. }
  8. /**
  9. * 导出word
  10. * @return 输入流
  11. * @throws IOException
  12. */
  13. public InputStream getDownloadFile() throws IOException{
  14. Configuration configuration = new Configuration();
  15. configuration.setDefaultEncoding("UTF-8");
  16. Template t=null;
  17. //FTL文件所存在的位置
  18. configuration.setClassForTemplateLoading(getClass(), "/csdc/tool/templates");
  19. //增加设置忽略空值异常
  20. // configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
  21. try {
  22. t = configuration.getTemplate("applyWord.ftl"); //文件名
  23. t.setEncoding("UTF-8");
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. Writer out = new StringWriter();
  28. // Writer out = new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream(), "UTF-8"));
  29. // OutputStreamWriter out = new OutputStreamWriter(new ByteArrayOutputStream());
  30. Map json = new HashMap();
  31. String appId = "4028d8a449e5dc8d0149e5de2b1d0001";
  32. Applicant app = dao.query(Applicant.class, appId);
  33. String charest1 = "ISO8859-1";
  34. fileFileName = "中心(助理研究员)岗位申请书.doc";
  35. fileFileName = new String(fileFileName.getBytes(), charest1);
  36. json.put("name", app.getName()!=null?app.getName():"");
  37. json.put("gender", app.getGender()!=null?app.getGender():"");
  38. json.put("department", app.getDepartment()!=null?app.getDepartment():"");
  39. json.put("major", app.getMajor()!=null?app.getMajor():"");
  40. json.put("startDate", app.getStartDate()!=null?app.getStartDate():"");
  41. json.put("graduateDate", app.getGraduateDate()!=null?app.getGraduateDate():"");
  42. json.put("email", app.getEmail()!=null?app.getEmail():"");
  43. json.put("qq", app.getQq()!=null?app.getQq():"");
  44. json.put("introducation", app.getIntroduction()!=null?app.getIntroduction():"");
  45. json.put("studentType", app.getStudentType()!=null?app.getStudentType():"");
  46. json.put("teacher", app.getTeacher()!=null?app.getTeacher():"");
  47. json.put("phone", app.getMobilePhone()!=null?app.getMobilePhone():"");
  48. json.put("address", app.getAddress()!=null?app.getAddress():"");
  49. try {
  50. t.process(json, out);
  51. } catch (TemplateException e) {
  52. e.printStackTrace();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. } finally{
  56. // out.close();
  57. }
  58. out.flush();
  59. byte[] a = out.toString().getBytes();
  60. ByteArrayInputStream b = new ByteArrayInputStream(a);
  61. out.close();
  62. return b;
  63. }

在这种方式下,当我的Writer类型的变量是通过Writer out = new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream(), "UTF-8"));或者OutputStreamWriter out = new OutputStreamWriter(new ByteArrayOutputStream());申明的时候,得到的文件永远都是打开之后只有
java.io.BufferedWriter或者java.io.OutputStreamWriter,没有其他任何内容。当我改为通过Writer out = new StringWriter();申明时,终于得到了一个大小正常的文件,但是无法打开,提示xml字符非法。我把这个doc文档重命名为xml文档打开看过,里面很多中文全部是乱码的,为了解决这个乱码我又尝试了各种棉编码解码等手段,都是失败告终。

三、转变struts的配置方式

最后,我来到了第三种思路,同样struts2配置是最简单的那种

  1. <action name="test" class="testAction" method="test">
  2. <result type="json"><param name="root">jsonMap</param></result>
  3. </action>

然后action层代码是

  1. /**
  2. * 导出word
  3. * @throws UnsupportedEncodingException
  4. */
  5. public String test() throws UnsupportedEncodingException {
  6. Configuration configuration = new Configuration();
  7. configuration.setDefaultEncoding("utf-8");
  8. Map data = new HashMap();
  9. String appId = "4028d8a449e5dc8d0149e5de2b1d0001";
  10. Applicant app = dao.query(Applicant.class, appId);
  11. // String charest1 = "ISO8859-1";
  12. // String charest2 = "utf-8";
  13. data.put("name", app.getName()!=null?app.getName():"");
  14. data.put("gender", app.getGender()!=null?app.getGender():"");
  15. data.put("department", app.getDepartment()!=null?app.getDepartment():"");
  16. data.put("major", app.getMajor()!=null?app.getMajor():"");
  17. data.put("startDate", app.getStartDate()!=null?app.getStartDate():"");
  18. data.put("graduateDate", app.getGraduateDate()!=null?app.getGraduateDate():"");
  19. data.put("email", app.getEmail()!=null?app.getEmail():"");
  20. data.put("qq", app.getQq()!=null?app.getQq():"");
  21. data.put("introducation", app.getIntroduction()!=null?app.getIntroduction():"");
  22. data.put("studentType", app.getStudentType()!=null?app.getStudentType():"");
  23. data.put("teacher", app.getTeacher()!=null?app.getTeacher():"");
  24. data.put("phone", app.getMobilePhone()!=null?app.getMobilePhone():"");
  25. data.put("address", app.getAddress()!=null?app.getAddress():"");
  26. configuration.setClassForTemplateLoading(getClass(), "/csdc/tool/templates");
  27. Template t = null;
  28. try {
  29. t = configuration.getTemplate("applyWord.ftl");//载入模版文件(把要导出的word模版另存为word xml就可以了)
  30. t.setEncoding("utf-8");
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. String fileName = "中心(助理研究员)岗位申请书.doc";
  35. fileName = new String(fileName.getBytes(), "ISO8859-1");
  36. ActionContext ctx = ActionContext.getContext();
  37. HttpServletResponse response = (HttpServletResponse) ctx
  38. .get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");
  39. response.setContentType("application/msword");
  40. try {
  41. response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
  42. response.setCharacterEncoding("utf-8");
  43. PrintWriter out = response.getWriter();
  44. t.process(data, out);
  45. out.close();
  46. } catch (UnsupportedEncodingException e) {
  47. e.printStackTrace();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. } catch (TemplateException e) {
  51. e.printStackTrace();
  52. }
  53. return SUCCESS;
  54. }

最终终于得到了正确的结果。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注