Struts2利用iText导出word文档(包含表格)以提供下载

      在公司实习期间,带我的老师让我实现一功能——在显示课表的页面上上点击“导出文件“时能以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里的配置如下:

Java代码 复制代码 收藏代码
  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>  
<!-- 保存为word文件 -->
       <action name="studentCurriculumWord" class="studentCurriculumWordAction">
       	  <result name="success" type="stream"> 
              <param name="contentType">application/vnd.ms-word</param> 
              <param name="contentDisposition">attachment;filename="studentCurriculum.doc"</param> 
              <param name="inputName">wordFile</param> 
          </result>
       </action>

        对应的Action代码如下:

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

posted on 2015-08-03 15:13  摇曳蒲公英  阅读(659)  评论(0编辑  收藏  举报

导航