使用iText在word文檔中插入復雜的表格
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; @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 ""; } }
}</pre>