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 ...
随机推荐
- EIP Core2.0开源
EIP Core2 权限管理系统 (交流群:495070603,作者:1039318332) 开源地址: https://gitee.com/sunzewei/eipcore2 https://git ...
- 如何大批量的识别图片上的文字,批量图片文字识别OCR软件系统
软件不需要安装,直接双击打开就可以用,废话不多说直接上图好了,方便说明问题 批量图片OCR(批量名片识别.批量照片识别等)识别,然后就下来研究了一下,下面是成果 使用步骤:打开单个图片识别,导入文件夹 ...
- ADO.NET中使用事务
using (SqlConnection conn = new SqlConnection(k2ConnStr)) { SqlCommand cmd = new SqlCommand(sql, con ...
- PHP上传图片基本代码示例
一.HTML代码如下: <form name="form2" method="post" action="?type=add" enc ...
- springboot搭建dubbo+zookeeper简单案例
背景:只是自己使用单机版zookeeper搭建dubbo的一个学习案例,记录成功的过程 1.搭建zookeeper坏境 使用docker来构建环境 1.1 拉取镜像:docker pull zooke ...
- Odoo中的字段显示方式和行为控制
在odoo的视图中,字段都是通过widget来控制显示效果和行为的. 一般情况下,不同类型的字段odoo会使用默认的widget来显示和控制它的行为. options以一种JSON对象的形 ...
- MySQL数据物理备份之tar打包备份
复制数据文件方式,可以使用cp或tar 1.停止服务 [root@localhost mysql]# systemctl stop mysqld [root@localhost mysql]# net ...
- Nginx+Mysql调优
使用nginx实现反向代理作用,具备负载均衡的功能. 接受客户端的请求 | nginx(宿主机) | |-------------------| web1 web2 (客户机) 原理: 与 ...
- 网传英特尔酷睿第十代桌面处理器(Comet Lake 14nm)规格
自从农企(AMD)2016年开始崛起时,牙膏厂(英特尔)就开始发力,陆续两代推出性价比颇高的桌面处理器, 第八代.第九代酷睿桌面处理器相当的给力,而第十代酷睿桌面处理器会很猛啊,据传从酷睿i3到酷睿i ...
- flask实战-个人博客-模板 --
模板 personalBlog采用典型的博客布局,左侧三分之二为主体,显示文章列表.正文:右侧三分之一为边栏,显示分为类列表.社交链接等.现在的工作是将HTML文件加工为模板,并创建对应的表单类,在模 ...