根據項目需求,客戶想生成一個帶統計表格、圖片和說明文字的word文件,今天整了很久,終於弄好了,下面給出代碼,原本想用POI,但找了很久只實現了excel中添加圖片的處理,最後不得不使用的是iText2.1.7實現的,最新版不一定好使,附件提供相關jar包
package com.test;
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.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2;
public class WordDemo {
public WordDemo() {
}
/**
* @param args
*/
public static void main(String[] args) {
WordDemo.createDoc();
}
/**
* 創建word文檔 步驟: 1,建立文檔 2,創建一個書寫器 3,打開文檔 4,向文檔中寫入數據(表格,圖片) 5,關閉文檔
*/
public static void createDoc() {
// 創建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);
/* 測試添加一張圖片 */
Image img = Image.getInstance("E:/ok.png");
document.add(img);
/* 測試再添加一張圖片 */
Image img2 = Image.getInstance("E:/ok.png");
document.add(img2);
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}