实例:
public class RTFCreate {
public static void main(String[] args) {
RTFCreate rtfCreate = new RTFCreate();
try {
rtfCreate.createRTF();
JOptionPane.showMessageDialog(null, "表格已经成功创建");
} catch (MalformedURLException ex) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息:" + ex
+ "\n错误原因可能是表格已经打开!");
ex.printStackTrace();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息:" + ex
+ "\n错误原因可能是表格已经打开!");
ex.printStackTrace();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息:" + ex
+ "\n错误原因可能是表格已经打开!");
ex.printStackTrace();
} catch (DocumentException ex) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息:" + ex
+ "\n错误原因可能是表格已经打开!");
ex.printStackTrace();
}
}
public void createRTF() throws FileNotFoundException, DocumentException,
MalformedURLException, IOException {
// 创建word文档
Document document = new Document(PageSize.A4);
// 输入word文档 创建名为testword的word文档 并指定路径
RtfWriter2.getInstance(document, new FileOutputStream("testword.rtf"));
document.open();
// 中文字体
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 12, Font.HELVETICA);
// 创建有3列的表格
Table table = new Table(3);
//设置表格的宽度
table.setWidth(80f);
document.add(new Paragraph("生成rft文档!", fontChinese));
document.add(new Paragraph("当前用户:"+"管理员", fontChinese));
table.setBorderWidth(1);
table.setBorderColor(new Color(0, 0, 255));
//表格的行间距和首部距离
table.setPadding(0);
table.setSpacing(0);
// 添加表头元素
Cell cell = new Cell("header");
cell.setHeader(true);
//设置单元格的背景颜色
cell.setBackgroundColor(Color.PINK);
cell.setColspan(3);
table.addCell(cell);
table.endHeaders();// 表头结束
// 表格主体
cell = new Cell("Example cell with colspan 1 and rowspan 2");
cell.setRowspan(2);
cell.setBorderColor(new Color(255, 0, 0));
table.addCell(cell);
table.addCell("1.1");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
table.addCell(new Paragraph("测试1", fontChinese));
table.addCell("big cell");
cell.setRowspan(2);
cell.setColspan(2);
table.addCell(cell);
table.addCell(new Paragraph("测试2", fontChinese));
document.add(table);
// 在表格末尾添加图片
Image png = Image.getInstance("gg1.gif");
png.scaleAbsolute(200,150);
document.add(png);
document.close();
}
}