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

我们看下如何使用itext插入表格。

要插入表格首先要创建Table对象

如下代码创建了一个2列的表格,声明表格对象至少要指定表格对象有几列。

Table table = new Table(2);

或者:

Table table = new Table(2,3);

以上代码表示创建一个2列3行的表格。

itext中提供了很多属性,我们可以设置表格的边框,设置cellspacing,cellpadding,以及backgroundColor等属性。

声明表格之后就需要向表格中插入单元格了,需要注意itext中的table只有Cell的概念,没有行的概念,因为在声明表格时必须指定该表格由几列组成,所以不会有问题。

下面我们声明一个Cell对象:

Cell cell = new Cell("HELLO WORLD");

很简单的创建了一个单元格对象,这个单元格中有文字HELLO WORLD.

你也可以先创建一个空的单元格,然后向单元格内插入任意的元素,例如:

Cell cell = new Cell();Paragraph pHello = new Paragraph("Hello");cell.add(pHello);

如果需要还可以通过cell.setRowspan(arg0);imgCell.setColspan(arg0)方法来设置单元格的RowSpan和ColSpan属性。

创建好Cell之后需要将Cell添加到Table中:

table.addCell(cell);

iText提供的在word文档中操作table的api很简单,下面有一个比较复杂的例子供参考:

其效果图,如下:

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 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;@Overridepublic String execute() throws Exception {// TODO Auto-generated method stubreturn 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 "";}}
}

转载于:https://blog.51cto.com/116833/1688695

使用iText在word文档中插入复杂的Table表格相关推荐

  1. C# 如何在Word文档中插入艺术字

    C# 如何在Word文档中插入艺术字 在Word文档中添加艺术字效果可以让文档的排版更加美观.本篇文章主要介绍如何使用C#和Spire.Doc组件在Word文档中插入艺术字. Spire.Doc支持多 ...

  2. 解决:word文档中插入照片有一部分不显示

    今天在word文档中插入照片的时候,有一部分被隐藏不显示 出现该问题的原因是段落设置的问题,行距是固定值 解决办法: 将行距改为1.5倍行距就可以了

  3. WORD文档中插入图片(1)

    (转) 在WORD文档中插入图片有两种方法:一种是添加到文档的文本层(嵌入型版式):一种是添加到文档的图形层(其他版式).     文本层的图片是不可以设置版式的,而图形层的版式是可以设置的,但只能是 ...

  4. C#操作Word(五)——在Word文档中插入图片

    实例说明 在Word文档的使用过程中,我们可以轻松的向文档中插入图片信息,那么,怎样使用C#向Word文档中插入图片呢?本实例将会介绍一种方法,可以方便的实现上述功能.实例运行效果如图1所示.   图 ...

  5. (转) 如何在Excel和Word文档中插入GIF动画

    Office Excel 和Word文档中插入图片很容易做到,但是要插入GIF动画,并且还要能让这个动画动起来,就不能依照普通的"插入 → 图片 → 来自文件"的方法了,否则的话即 ...

  6. C# Word文档中插入、提取图片,文字替换图片

    Download Files: http://www.c-sharpcorner.com/UploadFile/26b237/image-operations-using-word-document- ...

  7. word文档中插入公式的技巧--利用表格

    word文档中插入公式的技巧--利用表格 本人愚笨之前在word中加公式的时候,由于需要公式的编号右对齐,且公式居中.我就会在插入了公式之后打上一堆的空格,这样既费事儿,又弄的公式参差不齐,不是十分的 ...

  8. 计算机word插图教案,《在WORD文档中插入图片》教学设计

    一.教学设计思想 现代教育理论提出"学生是教学活动的主体,老师是教学活动的主导".教师的主导作用体现在组织.指导.帮助和促进学生的学习,充分发挥学生的主动性.积极性.创造性和合作性 ...

  9. Word控件Spire.Doc 【列表】教程:在 Word 文档中插入列表

    Spire.Doc for .NET是一款专门对 Word 文档进行操作的 .NET 类库.在于帮助开发人员无需安装 Microsoft Word情况下,轻松快捷高效地创建.编辑.转换和打印 Micr ...

最新文章

  1. 如何设计并实现一个秒杀系统?(含完整代码)
  2. 【翻译】Ext JS 5:为不同设备设置不同的主题
  3. 查询用户所有信息后只需要两个字段的信息_Excel VBA+ADO+SQL入门教程023:OpenSchema获取表信息...
  4. Python学习入门基础教程(learning Python)--2.3.5Python返回多个值问题
  5. Bug访问豆瓣403forbidden
  6. if语句和缩进部分是一个完整的代码块
  7. C++ 快速排序算法
  8. LeetCode 1277. 统计全为 1 的正方形子矩阵(DP)
  9. 真神器!在家也能控制公司的电脑了
  10. 论文赏析[NAACL19]一个更好更快更强的序列标注成分句法分析器
  11. Android自动化测试在多种屏幕下的注意事项
  12. Android--Menus
  13. Excel工作表保护在哪里撤销?
  14. 帝国CMS二次开发入门教程
  15. Java获取IP归属地
  16. aw36515闪光灯驱动ic调试
  17. KOF97判定框查看方法
  18. git的基本使用[远程库库操作 - GitHub]
  19. ln -sf是永久生效的吗linux,ln -s 软连接介绍
  20. IC数字芯片学习各类公众号汇总

热门文章

  1. 还在用Swagger生成接口文档?我推荐你试试它.....
  2. 程序员必备网站之一:No Design
  3. 分布式锁用 Redis 还是 Zookeeper?
  4. 2w字长文,让你瞬间拥有「调用链」开发经验
  5. 2019年9月全国程序员工资统计。
  6. 阮一峰在 GitHub 又一开源力作!
  7. 实操教程|PyTorch AutoGrad C++层实现
  8. 字节跳动年度《算法资料合集》首次公开,限时下载!
  9. 高效Transformer层出不穷,谷歌团队综述文章一网打尽
  10. 深度学习框架大战,我该选哪个?