Java使用iText生成word檔案的解決方案
阿新 • • 發佈:2018-12-19
轉自【http://www.31km.cn/post/450.html】
JAVA生成WORD檔案的方法目前有以下種:
一種是jacob 但是侷限於windows平臺 往往許多JAVA程式運行於其他作業系統 在此不討論該方案
一種是pio但是他的excel處理很程式 word模組還侷限於讀取word的文字內容,寫word檔案就更弱項了
本文介紹的是itext生成rtf檔案並儲存格式為word 此方案本人已實踐過 並已在專案中使用
用到的jar包:iText-2.1.5.jariText-rtf-2.1.4.jariTextAsian.jar
[java] view plain copy print?- package
- import java.awt.Color;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import com.lowagie.text.Cell;
- import com.lowagie.text.Document;
- import com.lowagie.text.DocumentException;
- import com.lowagie.text.Font;
- import com.lowagie.text.PageSize;
- import com.lowagie.text.Paragraph;
- import com.lowagie.text.Table;
- import com.lowagie.text.rtf.RtfWriter2;
- /**
- * 建立word文件 步驟:
- * 1,建立文件
- * 2,建立一個書寫器
- * 3,開啟文件
- * 4,向文件中寫入資料
- * 5,關閉文件
- */
- publicclass WordDemo {
- public WordDemo() {
- }
- /**
- * @param args
- */
- publicstaticvoid main(String[] args) {
- // 建立word文件,並設定紙張的大小
- Document document = new Document(PageSize.A4);
- try {
- RtfWriter2.getInstance(document,
- new FileOutputStream("E:/word.doc"));
- document.open();
- //設定合同頭
- Paragraph ph = new Paragraph();
- Font f = new Font();
- Paragraph p = new Paragraph("出口合同",
- new Font(Font.NORMAL, 18, Font.BOLDITALIC, new Color(0, 0, 0)) );
- p.setAlignment(1);
- document.add(p);
- ph.setFont(f);
- // 設定中文字型
- // BaseFont bfFont =
- // BaseFont.createFont("STSongStd-Light",
- "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
- // Font chinaFont = new Font();
- /*
- * 建立有三列的表格
- */
- Table table = new Table(4);
- document.add(new Paragraph("生成表格"));
- table.setBorderWidth(1);
- table.setBorderColor(Color.BLACK);
- table.setPadding(0);
- table.setSpacing(0);
- /*
- * 新增表頭的元素
- */
- Cell cell = new Cell("表頭");//單元格
- cell.setHeader(true);
- cell.setColspan(3);//設定表格為三列
- cell.setRowspan(3);//設定表格為三行
- table.addCell(cell);
- table.endHeaders();// 表頭結束
- // 表格的主體
- cell = new Cell("Example cell 2");
- cell.setRowspan(2);//當前單元格佔兩行,縱向跨度
- table.addCell(cell);
- table.addCell("1,1");
- table.addCell("1,2");
- table.addCell("1,3");
- table.addCell("1,4");
- table.addCell("1,5");
- table.addCell(new Paragraph("用java生成的表格1"));
- table.addCell(new Paragraph("用java生成的表格2"));
- table.addCell(new Paragraph("用java生成的表格3"));
- table.addCell(new Paragraph("用java生成的表格4"));
- document.add(new Paragraph("用java生成word檔案"));
- document.add(table);
- document.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (DocumentException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }