aademeng

需求:有一个给定的word文档,文档中有一个表格,该表格只有一个标题行。现在根据数据为表格增加行,并保留表格线条。

如下表格所示:

字段1 字段2 字段3 字段4 字段5 字段6

修改后的效果:

字段1 字段2 字段3 字段4 字段5 字段6
... ... ... ... ... ...
... ... ... ... ... ...
... ... ... ... ... ...

 

方案:使用POI读取并操作word文档。

 

代码:

poi使用两种方式操作word文档,理论上两种方式都是可以达到目标的,这里使用XWPFDocument方式实现表格的操作,参考以下代码:

 

  1.  
    //读取word源文件
  2.  
    FileInputStream fileInputStream = new FileInputStream("d:/xxx.docx");
  3.  
    // POIFSFileSystem pfs = new POIFSFileSystem(fileInputStream);
  4.  
    XWPFDocument document = new XWPFDocument(fileInputStream);
  5.  
    //获取所有表格
  6.  
    List<XWPFTable> tables = document.getTables();
  7.  
    //这里简单取第一个表格
  8.  
    XWPFTable table = tables.get(0);
  9.  
    //获取表头,这里没什么用,只是打印验证下
  10.  
    XWPFTableRow header = table.getRow(0);
  11.  
    //表格的插入行有两种方式,这里使用addNewRowBetween,因为这样会保留表格的样式,就像我们在word文档的表格中插入行一样。注意这里不要使用insertNewTableRow方法插入新行,这样插入的新行没有样式,很难看
  12.  
    table.addNewRowBetween(0, 1);
  13.  
    //获取到刚刚插入的行
  14.  
    XWPFTableRow row=table.getRow(1);
  15.  
    //设置单元格内容
  16.  
    row.getCell(0).setText("11111");
  17.  
    System.out.println(header.getCell(0).getText());
  18.  
    fileInputStream.close();
  19.  
    //写到目标文件
  20.  
    OutputStream output = new FileOutputStream("d:/xxx_new.docx");
  21.  
    document.write(output);
  22.  
    output.close();



小结:

上述代码实现了类似模板的功能,将word源文件当做模板,然后往模板表格中插入数据,最后保存。

 

 

 

转自:http://www.findsrc.com/java/detail/8669

 

分类:

技术点:

相关文章:

  • 2021-11-11
  • 2022-12-23
  • 2022-02-24
  • 2021-11-11
  • 2021-12-28
  • 2021-10-05
  • 2022-12-23
猜你喜欢
  • 2021-11-11
  • 2021-11-21
  • 2021-06-20
  • 2022-12-23
  • 2021-08-22
  • 2021-04-26
相关资源
相似解决方案