java Apache POI Word existing table insert row with cell style and formatting

后端 未结 2 1654
孤城傲影
孤城傲影 2021-01-14 15:24

I\'am a beginner in Apache POI and want to extend an existing table in the word template file with some rows. If I use that code below, the table will be extended with row b

2条回答
  •  逝去的感伤
    2021-01-14 16:01

    I had the similar situation and I got it to work in a smarter way.

    let's say we have table template(as shown in below image) in a word file(template) and we want to populate the table row data dynamically. For this method to work, we have to create a template row which already has the formatting we need for the new rows. You will be using the template row to create the new row and delete the template row after adding all the desired number of rows of same formatting.

        XWPFTable table; //this is the table to be populated..needs to be initialized  as per your need.
    
       //the row ID of the empty row, which is our template row with all the formatting in it
        int tempateRowId = 1;
    
        // the empty row
        XWPFTableRow rowTemplate = table.getRow(tempateRowId);
    
        // iterate over the reportData
         Arrays.stream(reportData).forEach(data -> {
        // create a new row from the template, which would copy the format of previous row
         XWPFTableRow oldRow = rowTemplate;
         CTRow ctrow = null;
           try {
                ctrow = CTRow.Factory.parse(oldRow.getCtRow().newInputStream());
               } catch (XmlException e) {e.printStackTrace();
               } catch (IOException e) { e.printStackTrace();
               }
    
        XWPFTableRow newRow = new XWPFTableRow(ctrow, table);
             newRow.getCell(0).setText(data.getDataForColumn1());
             newRow.getCell(1).setText(data.getDataForColumn2());
    
       // adding the newly created row tot he table   
        table.addRow(newRow);
    });
    
    table.removeRow(tempateRowId); // removing the template row
    

    }

提交回复
热议问题