Open office writer crashed when inserting table using java POI

后端 未结 1 2035
借酒劲吻你
借酒劲吻你 2021-01-29 03:59

I am trying to insert table using apache-poi in .docx format using open office..But the file is crashed every time i open the file

      XWPFDocument document= n         


        
相关标签:
1条回答
  • 2021-01-29 04:29

    Libreoffice/Openoffice needs a table grid to accept the column widths.

    This should work:

    import java.io.FileOutputStream;
    
    import org.apache.poi.xwpf.usermodel.*;
    
    import java.math.BigInteger;
    
    public class CreateWordTable {
     public static void main(String[] args) throws Exception {
    
      XWPFDocument document = new XWPFDocument();
    
      XWPFParagraph paragraph = document.createParagraph();
    
          //create table
          XWPFTable table = document.createTable();
    
          //create first row
          XWPFTableRow tableRowOne = table.getRow(0);
          tableRowOne.getCell(0).setText("col one, row one");
          tableRowOne.addNewTableCell().setText("col two, row one");
          tableRowOne.addNewTableCell().setText("col three, row one");
    
      //create CTTblGrid for this table with widths of the 3 columns. 
      //necessary for Libreoffice/Openoffice to accept the column widths.
      //values are in unit twentieths of a point (1/1440 of an inch)
      //first column = 2 inches width
      table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(2*1440));
      //other columns (2 in this case) also each 2 inches width
      for (int col = 1 ; col < 3; col++) {
       table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(2*1440));
      }
    
          //create second row
          XWPFTableRow tableRowTwo = table.createRow();
          tableRowTwo.getCell(0).setText("col one, row two");
          tableRowTwo.getCell(1).setText("col two, row two");
          tableRowTwo.getCell(2).setText("col three, row two");
    
          //create third row
          XWPFTableRow tableRowThree = table.createRow();
          tableRowThree.getCell(0).setText("col one, row three");
          tableRowThree.getCell(1).setText("col two, row three");
          tableRowThree.getCell(2).setText("col three, row three");
    
      paragraph = document.createParagraph();
    
      document.write(new FileOutputStream("CreateWordTable.docx"));
      document.close();
    
      System.out.println("CreateWordTable written successully");
     }
    }
    

    Btw.: Please always have at least one paragraph before and after the table. Else it is really impossible to get the cursor outside the table.

    0 讨论(0)
提交回复
热议问题