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里的配置如下:
- <!-- 保存为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>
- <!-- 保存为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代码如下:
- import java.awt.Color;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.util.List;
- import java.util.Map;
- import cn.com.wiscom.jwxk.entity.StudentCurriculum;
- import com.lowagie.text.Cell;
- import com.lowagie.text.Document;
- import com.lowagie.text.Element;
- import com.lowagie.text.Font;
- import com.lowagie.text.PageSize;
- import com.lowagie.text.Paragraph;
- import com.lowagie.text.Phrase;
- import com.lowagie.text.Table;
- import com.lowagie.text.rtf.RtfWriter2;
- import com.lowagie.text.rtf.style.RtfFont;
- import com.opensymphony.xwork2.ActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- /** 学生课表导出word author:yyli Sep 15, 2010 */
- public class StudentCurriculumWordAction extends ActionSupport {
- private static final long serialVersionUID = 2150958354251222076L;
- @Override
- public String execute() throws Exception {
- // TODO Auto-generated method stub
- return SUCCESS;
- }
- @SuppressWarnings( { "serial", "unchecked" })
- public InputStream getWordFile() throws Exception {
- Map<String, Object> session = ActionContext.getContext().getSession();
- List<StudentCurriculum> leftList = (List<StudentCurriculum>) session
- .get("stuCurriculumleftList");
- String[] stuCurriculumArray = (String[]) session
- .get("stuCurriculumrightArray");
- float totalXf = 0;
- /** 创建Document对象(word文档) author:yyli Sep 15, 2010 */
- Document doc = new Document(PageSize.A4);
- /** 新建字节数组输出流 author:yyli Sep 15, 2010 */
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- /** 建立一个书写器与document对象关联,通过书写器可以将文档写入到输出流中 author:yyli Sep 15, 2010 */
- RtfWriter2.getInstance(doc, baos);
- doc.open();
- /** 标题字体 author:yyli Sep 15, 2010 */
- RtfFont titleFont = new RtfFont("仿宋_GB2312", 12, Font.NORMAL,
- Color.BLACK);
- /** 正文字体 author:yyli Sep 15, 2010 */
- RtfFont contextFont = new RtfFont("仿宋_GB2312", 9, Font.NORMAL,
- Color.BLACK);
- /** 表格设置 author:yyli Sep 15, 2010 */
- Table table = new Table(12, 16);
- int[] withs = { 3, 9, 5, 4, 4, 3, 3, 14, 14, 14, 14, 14 };
- /** 设置每列所占比例 author:yyli Sep 15, 2010 */
- table.setWidths(withs);
- /** 表格所占页面宽度 author:yyli Sep 15, 2010 */
- table.setWidth(100);
- /** 居中显示 author:yyli Sep 15, 2010 */
- table.setAlignment(Element.ALIGN_CENTER);
- /** 自动填满 author:yyli Sep 15, 2010 */
- table.setAutoFillEmptyCells(true);
- /** 第一行(标题) author:yyli Sep 15, 2010 */
- String titleString = "东南大学 "
- + (String) session.get("selectXn")
- + "-"
- + String.valueOf(Integer.parseInt((String) session
- .get("selectXn"))) + " 学年第 "
- + (String) session.get("selectXq") + "学期 学生个人课表";
- Paragraph title = new Paragraph(titleString);
- // 设置标题格式对其方式
- title.setAlignment(Element.ALIGN_CENTER);
- title.setFont(titleFont);
- doc.add(title);
- /** 第二行(正文) author:yyli Sep 15, 2010 */
- String contextString = "院系:" + (String) session.get("yxmc") + " 专业:"
- + (String) session.get("zymc") + " 学号:"
- + (String) session.get("xh") + " 一卡通号:"
- + (String) session.get("userId") + " 姓名:"
- + (String) session.get("stuName");
- Paragraph context = new Paragraph(contextString);
- // 正文格式对齐方式
- context.setAlignment(Element.ALIGN_CENTER);
- context.setFont(contextFont);
- // 与上一段落(标题)的行距
- context.setSpacingBefore(10);
- // 设置第一行空的列数(缩进)
- // context.setFirstLineIndent(20);
- doc.add(context);
- /** 第三行(表格) author:yyli Sep 15, 2010 */
- Cell[] cellHeaders = new Cell[11];
- cellHeaders[0] = new Cell(new Phrase("序号", contextFont));
- cellHeaders[1] = new Cell(new Phrase("课程名称", contextFont));
- cellHeaders[2] = new Cell(new Phrase("教师", contextFont));
- cellHeaders[3] = new Cell(new Phrase("学分", contextFont));
- cellHeaders[4] = new Cell(new Phrase("上课周次", contextFont));
- cellHeaders[5] = new Cell(new Phrase(" ", contextFont));
- cellHeaders[5].setColspan(2);
- cellHeaders[6] = new Cell(new Phrase("星期一", contextFont));
- cellHeaders[7] = new Cell(new Phrase("星期二", contextFont));
- cellHeaders[8] = new Cell(new Phrase("星期三", contextFont));
- cellHeaders[9] = new Cell(new Phrase("星期四", contextFont));
- cellHeaders[10] = new Cell(new Phrase("星期五", contextFont));
- for (int i = 0; i < 11; i++) {
- /** 居中显示 author:yyli Sep 15, 2010 */
- cellHeaders[i].setHorizontalAlignment(Element.ALIGN_CENTER);
- /** 纵向居中显示 author:yyli Sep 15, 2010 */
- cellHeaders[i].setVerticalAlignment(Element.ALIGN_MIDDLE);
- table.addCell(cellHeaders[i]);
- }
- /** 向表格填充数据 author:yyli Sep 15, 2010 */
- for (int i = 0; i < 15; i++) {
- /** 第0列 author:yyli Sep 15, 2010 */
- Cell cell0 = new Cell(
- new Phrase(String.valueOf(i + 1), contextFont));
- cell0.setHorizontalAlignment(Element.ALIGN_CENTER);
- cell0.setVerticalAlignment(Element.ALIGN_MIDDLE);
- table.addCell(cell0);
- /** 第1-4列 author:yyli Sep 15, 2010 */
- Cell[] cell1_4 = new Cell[4];
- if (i < leftList.size()) {
- cell1_4[0] = new Cell(new Phrase(str_changenbsp(leftList.get(i)
- .getKcmc()), contextFont));
- cell1_4[1] = new Cell(new Phrase(str_changenbsp(leftList.get(i)
- .getJsxm()), contextFont));
- cell1_4[2] = new Cell(new Phrase(str_changenbsp(leftList.get(i)
- .getXf()), contextFont));
- cell1_4[3] = new Cell(new Phrase(str_changenbsp(leftList.get(i)
- .getJszc()), contextFont));
- }
- for (int n = 0; n < cell1_4.length; n++) {
- cell1_4[n].setHorizontalAlignment(Element.ALIGN_CENTER);
- cell1_4[n].setVerticalAlignment(Element.ALIGN_MIDDLE);
- table.addCell(cell1_4[n]);
- }
- /** 第5列 author:yyli Sep 15, 2010 */
- Cell cell5 = null;
- if (i == 0) {
- cell5 = new Cell(new Phrase("上午", contextFont));
- cell5.setRowspan(5);
- }
- if (i == 5) {
- cell5 = new Cell(new Phrase("下午", contextFont));
- cell5.setRowspan(5);
- }
- if (i == 10) {
- cell5 = new Cell(new Phrase("晚上", contextFont));
- cell5.setRowspan(2);
- }
- if (i == 12) {
- cell5 = new Cell(new Phrase("周六", contextFont));
- cell5.setColspan(2);
- }
- if (i == 13) {
- cell5 = new Cell(new Phrase("周日", contextFont));
- cell5.setColspan(2);
- }
- if (i == 14) {
- cell5 = new Cell(new Phrase("备注", contextFont));
- cell5.setColspan(2);
- }
- if (cell5 != null) {
- cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
- cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
- table.addCell(cell5);
- }
- /** 第6列 author:yyli Sep 15, 2010 */
- if (i < 12) {
- Cell cell2 = new Cell(new Phrase(String.valueOf(i + 1),
- contextFont));
- cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
- cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
- table.addCell(cell2);
- }
- /** 第7-11列 author:yyli Sep 15, 2010 */
- if (i == 0 || i == 5 || i == 10) {
- Cell[] cell7_11 = new Cell[5];
- for (int n = 0; n < 5; n++) {
- cell7_11[n] = new Cell(new Phrase(
- str_changebr(stuCurriculumArray[i + n]),
- contextFont));
- cell7_11[n].setHorizontalAlignment(Element.ALIGN_CENTER);
- cell7_11[n].setVerticalAlignment(Element.ALIGN_MIDDLE);
- if (i == 0 || i == 5) {
- cell7_11[n].setRowspan(5);
- } else {
- cell7_11[n].setRowspan(2);
- }
- table.addCell(cell7_11[n]);
- }
- }
- Cell cell7 = null;
- if (i == 12) {
- cell7 = new Cell(new Phrase(
- str_changebr(stuCurriculumArray[15]), contextFont));
- }
- if (i == 13) {
- cell7 = new Cell(new Phrase(
- str_changebr(stuCurriculumArray[16]), contextFont));
- }
- if (i == 14) {
- cell7 = new Cell(new Phrase(
- str_changebr(stuCurriculumArray[17]), contextFont));
- }
- if (cell7 != null) {
- cell7.setColspan(5);
- cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
- cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);
- table.addCell(cell7);
- }
- }
- doc.add(table);
- doc.close();
- // 得到输入流
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- baos.close();
- return bais;
- }
- public String str_changenbsp(String str) {
- if (str != null) {
- return str.replaceAll(" ", "");
- } else {
- return "";
- }
- }
- public String str_changebr(String str) {
- if (str != null) {
- return str.replaceAll("<br>", "\n");
- } else {
- return "";
- }
- }
- }
Struts2利用iText导出word文档(包含表格)以提供下载的更多相关文章
- 使用Spire.Doc组件利用模板导出Word文档
以前一直是用Office的组件实现Word文档导出,但是让客户在服务器安装Office,涉及到版权:而且Office安装,包括权限配置也是比较麻烦. 现在流行使用第三方组件来实现对Office的操作, ...
- 利用标签导出Word文档
1 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; us ...
- java用iText导出word文档
1.需要导入的jar包 2.导出word并下载其实是分两步的. 第一步是将需要导出的数据导出(上传)到服务器上 第二步是将服务器上的文档下载到本地 3. 第一步.上传文档 (1)设置响应信息以及构造上 ...
- 利用NPOI导出Word文档帮助类
/// <summary> /// NPOI操作Word /// </summary> public class NpoiWordHelper { /// <summar ...
- MindManager导出Word文档功能介绍
Mindmanager思维导图软件作为一款能与Microsoft office软件无缝集成的思维导图软件,支持Word文档的快速导入与导出,并支持Word文档的目录生成.模板套用等,极大地方便了用户完 ...
- .NET通过调用Office组件导出Word文档
.NET通过调用Office组件导出Word文档 最近做项目需要实现一个客户端下载word表格的功能,该功能是用户点击"下载表格",服务端将该用户的数据查询出来并生成数据到Word ...
- C# 导出word文档及批量导出word文档(4)
接下来是批量导出word文档和批量打印word文件,批量导出word文档和批量打印word文件的思路差不多,只是批量打印不用打包压缩文件,而是把所有文件合成一个word,然后通过js来调用 ...
- freemarker导出word文档——WordXML格式解析
前不久,公司一个项目需要实现导出文档的功能,之前是一个同事在做,做了3个星期,终于完成了,但是在项目上线之后却发现导出的文档有问题,此时,这个同事已经离职,我自然成为接班者,要把导出功能实现,但是我看 ...
- 自动生成并导出word文档
今天很荣幸又破解一现实难题:自动生成并导出word文档 先看页面效果: word效果: 代码: 先搭建struts2项目 创建action,并在struts.xml完成注册 <?xml vers ...
随机推荐
- 微信小程序页面调用自定义组件内的事件
微信小程序页面调用自定义组件内的事件 page page.json { "usingComponents": { "my-component": ". ...
- ES6入门系列 ----- Reflect
Reflect 是ES6 为了操作对象而提供的新的API, 目的是: 将Object 上一些明显属于语言内部的方法,比如 Object.defineProperty 放到 Reflect对象上 ...
- String类常用功能
String类常用功能 判断: boolean equals(Object obj) boolean equalsIgnoreCase(String str) //忽略大小写 boolean star ...
- vue-cli的安装及版本查看更新
vue-cli安装 npm install vue-cli -g vue-cli的版本查看 vue -V vue-cli的3.0+以后使用的不是vue-cli了,如果用以上的安装命令安装的并不是最新版 ...
- html书写行内元素时-tab和换行会在行内元素间引入间距
目录 html文本中的控制字符会被解析为文本节点 书写行内元素时,换行符LF与水平制表符HT会引入莫名的元素间间隔 其他控制字符是否会引入间距的验证 html文本中的控制字符会被解析为文本节点 举例: ...
- 实验吧——认真一点(绕过空格,逗号,关键字过滤等 sql盲注)
题目地址:http://ctf5.shiyanbar.com/web/earnest/index.php 过滤和拦截了某些东西,我经过多次尝试,最终构造的是 1'=(ascii(mid((select ...
- ELK日志系统之说说logstash的各种配置
当我们在设置配置logstash的conf文件内容时,日志数据的来源有以下几种配置: tcp形式:一个项目或其他日志数据来源用tcp协议的远程传输方式,将日志数据传入logstash input { ...
- 串口 PLC 编程FAQ
1. 不要频繁打开关闭串口,这是个耗时的过程,如果多个工位都争夺串口资源,则会出现卡顿,死锁. 2. PLC 的读写估计100毫秒,如果并发的写,有的写操作会失败,需要Delay或重试. 3. 通常一 ...
- Odoo报表的report标签和报表格式定义
转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10826329.html 一:Report标签 report标签可用于定义一条报表记录.属性有: 1) ...
- 【java异常】redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
产生此错误的原因通常是: 一.Redis没有启动: 我自己遇到一次这样的问题.汗! 二.由于防火墙原因无法连接到Redis; 1.服务器防火墙入站规则. 2.访问Redis的应用程序所在主机的出站规则 ...