在公司实习期间,带我的老师让我实现一功能——在显示课表的页面上上点击“导出文件“时能以word文档形式下载课表。将课表导出到excel里的功能他们已经实现了,用的是Struts2+poi实现的。poi对excel表格操作能力很强,但是对word文档的支持一直没有更新,操作能力有限。

iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf 的文档,而且可以将XML、Html文件转化为PDF文件。

使用了iText的iText-2.1.7.jar和iText-rtf-2.1.7.jar(可以到官网上下载各个版本),借助这两个jar可生成rtf格式的文档,而指定文件后缀名时指定为.doc即为word文档。

点击页面上”导出课表“下载得到的word文档效果图:

struts.xml里的配置如下:

  1. <!-- 保存为word文件 -->
  2. <action name="studentCurriculumWord" class="studentCurriculumWordAction">
  3. <result name="success" type="stream">
  4. <param name="contentType">application/vnd.ms-word</param>
  5. <param name="contentDisposition">attachment;filename="studentCurriculum.doc"</param>
  6. <param name="inputName">wordFile</param>
  7. </result>
  8. </action>
  1. <!-- 保存为word文件 -->
  2. <action name="studentCurriculumWord" class="studentCurriculumWordAction">
  3. <result name="success" type="stream">
  4. <param name="contentType">application/vnd.ms-word</param>
  5. <param name="contentDisposition">attachment;filename="studentCurriculum.doc"</param>
  6. <param name="inputName">wordFile</param>
  7. </result>
  8. </action>

对应的Action代码如下:

  1. import java.awt.Color;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.InputStream;
  5. import java.util.List;
  6. import java.util.Map;
  7. import cn.com.wiscom.jwxk.entity.StudentCurriculum;
  8. import com.lowagie.text.Cell;
  9. import com.lowagie.text.Document;
  10. import com.lowagie.text.Element;
  11. import com.lowagie.text.Font;
  12. import com.lowagie.text.PageSize;
  13. import com.lowagie.text.Paragraph;
  14. import com.lowagie.text.Phrase;
  15. import com.lowagie.text.Table;
  16. import com.lowagie.text.rtf.RtfWriter2;
  17. import com.lowagie.text.rtf.style.RtfFont;
  18. import com.opensymphony.xwork2.ActionContext;
  19. import com.opensymphony.xwork2.ActionSupport;
  20. /** 学生课表导出word author:yyli Sep 15, 2010 */
  21. public class StudentCurriculumWordAction extends ActionSupport {
  22. private static final long serialVersionUID = 2150958354251222076L;
  23. @Override
  24. public String execute() throws Exception {
  25. // TODO Auto-generated method stub
  26. return SUCCESS;
  27. }
  28. @SuppressWarnings( { "serial", "unchecked" })
  29. public InputStream getWordFile() throws Exception {
  30. Map<String, Object> session = ActionContext.getContext().getSession();
  31. List<StudentCurriculum> leftList = (List<StudentCurriculum>) session
  32. .get("stuCurriculumleftList");
  33. String[] stuCurriculumArray = (String[]) session
  34. .get("stuCurriculumrightArray");
  35. float totalXf = 0;
  36. /** 创建Document对象(word文档) author:yyli Sep 15, 2010 */
  37. Document doc = new Document(PageSize.A4);
  38. /** 新建字节数组输出流 author:yyli Sep 15, 2010 */
  39. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  40. /** 建立一个书写器与document对象关联,通过书写器可以将文档写入到输出流中 author:yyli Sep 15, 2010 */
  41. RtfWriter2.getInstance(doc, baos);
  42. doc.open();
  43. /** 标题字体 author:yyli Sep 15, 2010 */
  44. RtfFont titleFont = new RtfFont("仿宋_GB2312", 12, Font.NORMAL,
  45. Color.BLACK);
  46. /** 正文字体 author:yyli Sep 15, 2010 */
  47. RtfFont contextFont = new RtfFont("仿宋_GB2312", 9, Font.NORMAL,
  48. Color.BLACK);
  49. /** 表格设置 author:yyli Sep 15, 2010 */
  50. Table table = new Table(12, 16);
  51. int[] withs = { 3, 9, 5, 4, 4, 3, 3, 14, 14, 14, 14, 14 };
  52. /** 设置每列所占比例 author:yyli Sep 15, 2010 */
  53. table.setWidths(withs);
  54. /** 表格所占页面宽度 author:yyli Sep 15, 2010 */
  55. table.setWidth(100);
  56. /** 居中显示 author:yyli Sep 15, 2010 */
  57. table.setAlignment(Element.ALIGN_CENTER);
  58. /** 自动填满 author:yyli Sep 15, 2010 */
  59. table.setAutoFillEmptyCells(true);
  60. /** 第一行(标题) author:yyli Sep 15, 2010 */
  61. String titleString = "东南大学 "
  62. + (String) session.get("selectXn")
  63. + "-"
  64. + String.valueOf(Integer.parseInt((String) session
  65. .get("selectXn"))) + " 学年第 "
  66. + (String) session.get("selectXq") + "学期 学生个人课表";
  67. Paragraph title = new Paragraph(titleString);
  68. // 设置标题格式对其方式
  69. title.setAlignment(Element.ALIGN_CENTER);
  70. title.setFont(titleFont);
  71. doc.add(title);
  72. /** 第二行(正文) author:yyli Sep 15, 2010 */
  73. String contextString = "院系:" + (String) session.get("yxmc") + "    专业:"
  74. + (String) session.get("zymc") + "    学号:"
  75. + (String) session.get("xh") + "    一卡通号:"
  76. + (String) session.get("userId") + "    姓名:"
  77. + (String) session.get("stuName");
  78. Paragraph context = new Paragraph(contextString);
  79. // 正文格式对齐方式
  80. context.setAlignment(Element.ALIGN_CENTER);
  81. context.setFont(contextFont);
  82. // 与上一段落(标题)的行距
  83. context.setSpacingBefore(10);
  84. // 设置第一行空的列数(缩进)
  85. // context.setFirstLineIndent(20);
  86. doc.add(context);
  87. /** 第三行(表格) author:yyli Sep 15, 2010 */
  88. Cell[] cellHeaders = new Cell[11];
  89. cellHeaders[0] = new Cell(new Phrase("序号", contextFont));
  90. cellHeaders[1] = new Cell(new Phrase("课程名称", contextFont));
  91. cellHeaders[2] = new Cell(new Phrase("教师", contextFont));
  92. cellHeaders[3] = new Cell(new Phrase("学分", contextFont));
  93. cellHeaders[4] = new Cell(new Phrase("上课周次", contextFont));
  94. cellHeaders[5] = new Cell(new Phrase(" ", contextFont));
  95. cellHeaders[5].setColspan(2);
  96. cellHeaders[6] = new Cell(new Phrase("星期一", contextFont));
  97. cellHeaders[7] = new Cell(new Phrase("星期二", contextFont));
  98. cellHeaders[8] = new Cell(new Phrase("星期三", contextFont));
  99. cellHeaders[9] = new Cell(new Phrase("星期四", contextFont));
  100. cellHeaders[10] = new Cell(new Phrase("星期五", contextFont));
  101. for (int i = 0; i < 11; i++) {
  102. /** 居中显示 author:yyli Sep 15, 2010 */
  103. cellHeaders[i].setHorizontalAlignment(Element.ALIGN_CENTER);
  104. /** 纵向居中显示 author:yyli Sep 15, 2010 */
  105. cellHeaders[i].setVerticalAlignment(Element.ALIGN_MIDDLE);
  106. table.addCell(cellHeaders[i]);
  107. }
  108. /** 向表格填充数据 author:yyli Sep 15, 2010 */
  109. for (int i = 0; i < 15; i++) {
  110. /** 第0列 author:yyli Sep 15, 2010 */
  111. Cell cell0 = new Cell(
  112. new Phrase(String.valueOf(i + 1), contextFont));
  113. cell0.setHorizontalAlignment(Element.ALIGN_CENTER);
  114. cell0.setVerticalAlignment(Element.ALIGN_MIDDLE);
  115. table.addCell(cell0);
  116. /** 第1-4列 author:yyli Sep 15, 2010 */
  117. Cell[] cell1_4 = new Cell[4];
  118. if (i < leftList.size()) {
  119. cell1_4[0] = new Cell(new Phrase(str_changenbsp(leftList.get(i)
  120. .getKcmc()), contextFont));
  121. cell1_4[1] = new Cell(new Phrase(str_changenbsp(leftList.get(i)
  122. .getJsxm()), contextFont));
  123. cell1_4[2] = new Cell(new Phrase(str_changenbsp(leftList.get(i)
  124. .getXf()), contextFont));
  125. cell1_4[3] = new Cell(new Phrase(str_changenbsp(leftList.get(i)
  126. .getJszc()), contextFont));
  127. }
  128. for (int n = 0; n < cell1_4.length; n++) {
  129. cell1_4[n].setHorizontalAlignment(Element.ALIGN_CENTER);
  130. cell1_4[n].setVerticalAlignment(Element.ALIGN_MIDDLE);
  131. table.addCell(cell1_4[n]);
  132. }
  133. /** 第5列 author:yyli Sep 15, 2010 */
  134. Cell cell5 = null;
  135. if (i == 0) {
  136. cell5 = new Cell(new Phrase("上午", contextFont));
  137. cell5.setRowspan(5);
  138. }
  139. if (i == 5) {
  140. cell5 = new Cell(new Phrase("下午", contextFont));
  141. cell5.setRowspan(5);
  142. }
  143. if (i == 10) {
  144. cell5 = new Cell(new Phrase("晚上", contextFont));
  145. cell5.setRowspan(2);
  146. }
  147. if (i == 12) {
  148. cell5 = new Cell(new Phrase("周六", contextFont));
  149. cell5.setColspan(2);
  150. }
  151. if (i == 13) {
  152. cell5 = new Cell(new Phrase("周日", contextFont));
  153. cell5.setColspan(2);
  154. }
  155. if (i == 14) {
  156. cell5 = new Cell(new Phrase("备注", contextFont));
  157. cell5.setColspan(2);
  158. }
  159. if (cell5 != null) {
  160. cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
  161. cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
  162. table.addCell(cell5);
  163. }
  164. /** 第6列 author:yyli Sep 15, 2010 */
  165. if (i < 12) {
  166. Cell cell2 = new Cell(new Phrase(String.valueOf(i + 1),
  167. contextFont));
  168. cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
  169. cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
  170. table.addCell(cell2);
  171. }
  172. /** 第7-11列 author:yyli Sep 15, 2010 */
  173. if (i == 0 || i == 5 || i == 10) {
  174. Cell[] cell7_11 = new Cell[5];
  175. for (int n = 0; n < 5; n++) {
  176. cell7_11[n] = new Cell(new Phrase(
  177. str_changebr(stuCurriculumArray[i + n]),
  178. contextFont));
  179. cell7_11[n].setHorizontalAlignment(Element.ALIGN_CENTER);
  180. cell7_11[n].setVerticalAlignment(Element.ALIGN_MIDDLE);
  181. if (i == 0 || i == 5) {
  182. cell7_11[n].setRowspan(5);
  183. } else {
  184. cell7_11[n].setRowspan(2);
  185. }
  186. table.addCell(cell7_11[n]);
  187. }
  188. }
  189. Cell cell7 = null;
  190. if (i == 12) {
  191. cell7 = new Cell(new Phrase(
  192. str_changebr(stuCurriculumArray[15]), contextFont));
  193. }
  194. if (i == 13) {
  195. cell7 = new Cell(new Phrase(
  196. str_changebr(stuCurriculumArray[16]), contextFont));
  197. }
  198. if (i == 14) {
  199. cell7 = new Cell(new Phrase(
  200. str_changebr(stuCurriculumArray[17]), contextFont));
  201. }
  202. if (cell7 != null) {
  203. cell7.setColspan(5);
  204. cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
  205. cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);
  206. table.addCell(cell7);
  207. }
  208. }
  209. doc.add(table);
  210. doc.close();
  211. // 得到输入流
  212. ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
  213. baos.close();
  214. return bais;
  215. }
  216. public String str_changenbsp(String str) {
  217. if (str != null) {
  218. return str.replaceAll("&nbsp;", "");
  219. } else {
  220. return "";
  221. }
  222. }
  223. public String str_changebr(String str) {
  224. if (str != null) {
  225. return str.replaceAll("<br>", "\n");
  226. } else {
  227. return "";
  228. }
  229. }
  230. }

Struts2利用iText导出word文档(包含表格)以提供下载的更多相关文章

  1. 使用Spire.Doc组件利用模板导出Word文档

    以前一直是用Office的组件实现Word文档导出,但是让客户在服务器安装Office,涉及到版权:而且Office安装,包括权限配置也是比较麻烦. 现在流行使用第三方组件来实现对Office的操作, ...

  2. 利用标签导出Word文档

    1 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; us ...

  3. java用iText导出word文档

    1.需要导入的jar包 2.导出word并下载其实是分两步的. 第一步是将需要导出的数据导出(上传)到服务器上 第二步是将服务器上的文档下载到本地 3. 第一步.上传文档 (1)设置响应信息以及构造上 ...

  4. 利用NPOI导出Word文档帮助类

    /// <summary> /// NPOI操作Word /// </summary> public class NpoiWordHelper { /// <summar ...

  5. MindManager导出Word文档功能介绍

    Mindmanager思维导图软件作为一款能与Microsoft office软件无缝集成的思维导图软件,支持Word文档的快速导入与导出,并支持Word文档的目录生成.模板套用等,极大地方便了用户完 ...

  6. .NET通过调用Office组件导出Word文档

    .NET通过调用Office组件导出Word文档 最近做项目需要实现一个客户端下载word表格的功能,该功能是用户点击"下载表格",服务端将该用户的数据查询出来并生成数据到Word ...

  7. C# 导出word文档及批量导出word文档(4)

          接下来是批量导出word文档和批量打印word文件,批量导出word文档和批量打印word文件的思路差不多,只是批量打印不用打包压缩文件,而是把所有文件合成一个word,然后通过js来调用 ...

  8. freemarker导出word文档——WordXML格式解析

    前不久,公司一个项目需要实现导出文档的功能,之前是一个同事在做,做了3个星期,终于完成了,但是在项目上线之后却发现导出的文档有问题,此时,这个同事已经离职,我自然成为接班者,要把导出功能实现,但是我看 ...

  9. 自动生成并导出word文档

    今天很荣幸又破解一现实难题:自动生成并导出word文档 先看页面效果: word效果: 代码: 先搭建struts2项目 创建action,并在struts.xml完成注册 <?xml vers ...

随机推荐

  1. 微信小程序页面调用自定义组件内的事件

    微信小程序页面调用自定义组件内的事件 page page.json { "usingComponents": { "my-component": ". ...

  2. ES6入门系列 ----- Reflect

    Reflect   是ES6 为了操作对象而提供的新的API, 目的是: 将Object 上一些明显属于语言内部的方法,比如 Object.defineProperty  放到 Reflect对象上 ...

  3. String类常用功能

    String类常用功能 判断: boolean equals(Object obj) boolean equalsIgnoreCase(String str) //忽略大小写 boolean star ...

  4. vue-cli的安装及版本查看更新

    vue-cli安装 npm install vue-cli -g vue-cli的版本查看 vue -V vue-cli的3.0+以后使用的不是vue-cli了,如果用以上的安装命令安装的并不是最新版 ...

  5. html书写行内元素时-tab和换行会在行内元素间引入间距

    目录 html文本中的控制字符会被解析为文本节点 书写行内元素时,换行符LF与水平制表符HT会引入莫名的元素间间隔 其他控制字符是否会引入间距的验证 html文本中的控制字符会被解析为文本节点 举例: ...

  6. 实验吧——认真一点(绕过空格,逗号,关键字过滤等 sql盲注)

    题目地址:http://ctf5.shiyanbar.com/web/earnest/index.php 过滤和拦截了某些东西,我经过多次尝试,最终构造的是 1'=(ascii(mid((select ...

  7. ELK日志系统之说说logstash的各种配置

    当我们在设置配置logstash的conf文件内容时,日志数据的来源有以下几种配置: tcp形式:一个项目或其他日志数据来源用tcp协议的远程传输方式,将日志数据传入logstash input { ...

  8. 串口 PLC 编程FAQ

    1. 不要频繁打开关闭串口,这是个耗时的过程,如果多个工位都争夺串口资源,则会出现卡顿,死锁. 2. PLC 的读写估计100毫秒,如果并发的写,有的写操作会失败,需要Delay或重试. 3. 通常一 ...

  9. Odoo报表的report标签和报表格式定义

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10826329.html 一:Report标签     report标签可用于定义一条报表记录.属性有: 1) ...

  10. 【java异常】redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool

    产生此错误的原因通常是: 一.Redis没有启动: 我自己遇到一次这样的问题.汗! 二.由于防火墙原因无法连接到Redis; 1.服务器防火墙入站规则. 2.访问Redis的应用程序所在主机的出站规则 ...