java 生成word文档 通过(iText)

 

实例:

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();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值