Apache POI merge cells from a table in a Word document

后端 未结 3 1750
鱼传尺愫
鱼传尺愫 2020-12-18 06:58

I need to have a table with the cells on the first and second row merged.

Something like this:

Image of table (I can\'t post pics) http://i.stack.imgur.com/d

相关标签:
3条回答
  • 2020-12-18 07:36

    It seems xml has to be removed as well:

     XWPFTableCell removed = tableRow.getCell(idx);
     removed.getCTTc().newCursor().removeXml();
     tableRow.removeCell(idx);
    
    0 讨论(0)
  • 2020-12-18 07:44

    To merge horizontally/vertically you need to create 2 CTHMerge and use the setVal:

    • one for the cells that you will remain (STMerge.RESTART);
    • a second one for the merged cells (STMerge.CONTINUE);

    a) example of a horizontal merge for a 2x2 table:

    |___________|___________| --> |___________ ___________|
    |___________|___________| --> |___________ ___________|

    // First Row
    CTHMerge hMerge = CTHMerge.Factory.newInstance();
    vmerge.setVal(STMerge.RESTART);
    table.getRow(0).getCell(0).getCTTc().getTcPr().setHMerge(hMerge);
    table.getRow(1).getCell(0).getCTTc().getTcPr().setHMerge(hMerge);
    
    // Secound Row cell will be merged/"deleted"
    CTHMerge hMerge1 = CTHMerge.Factory.newInstance();
    hMerge.setVal(STMerge.CONTINUE);
    table.getRow(0).getCell(1).getCTTc().getTcPr().setHMerge(hMerge1);
    table.getRow(1).getCell(1).getCTTc().getTcPr().setHMerge(hMerge1);
    

    b) example of a vertical merge:

     // First Row
    CTVMerge vmerge = CTVMerge.Factory.newInstance();
    vmerge.setVal(STMerge.RESTART);
    table.getRow(0).getCell(0).getCTTc().getTcPr().setVMerge(vmerge);
    table.getRow(0).getCell(1).getCTTc().getTcPr().setVMerge(vmerge);
    
     // Secound Row cell will be merged 
    CTVMerge vmerge1 = CTVMerge.Factory.newInstance();
    vmerge.setVal(STMerge.CONTINUE);
    table.getRow(1).getCell(0).getCTTc().getTcPr().setVMerge(vmerge1);
    table.getRow(1).getCell(1).getCTTc().getTcPr().setVMerge(vmerge1);
    
    0 讨论(0)
  • 2020-12-18 07:47

    You can also avoid creating the extra cells, instead of removing cells after the merge. It requires adding rows and cells sequentially (instead of using document.createTable())

    For your example it would be:

    1. Create first rows with 1 cell, set text
    2. Create next row, and in it create new cell, set text
    3. Create next rows and set text
    4. Merge
    0 讨论(0)
提交回复
热议问题