TableProcessor.java

package org.docascode.api.core.office.table;

import org.apache.commons.io.FilenameUtils;
import org.docascode.api.core.errors.DocAsCodeException;
import org.docascode.api.core.office.Utils;
import org.docascode.api.listener.APIEventListener;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.Tr;

import java.io.File;
import java.util.List;

public class TableProcessor extends APIEventListener {
    public static void insertRow(File file, Table table) throws DocAsCodeException {
        try {
            String extension = FilenameUtils.getExtension(file.getAbsolutePath());
            WordprocessingMLPackage openPackage;
            switch (extension) {
                case "docx":
                case "docm":
                    openPackage = WordprocessingMLPackage.load(file);
                    break;
                default:
                    return;
            }
            List<Tbl> listTables = Utils.getTargetElements(openPackage.getMainDocumentPart(), Tbl.class);
            Tbl tbl  = listTables.get(table.getNum());
            List<Tr> listRows = Utils.getTargetElements(tbl,Tr.class);
            Tr templateRow = listRows.get(listRows.size()-1);
            for (Row row : table.getRows()){
                if(table.getParagraphFormat()!= null){
                    row.setParagraphFormat(table.getParagraphFormat());
                }
                tbl.getContent().add(row.toTr(templateRow));
            }
            openPackage.save(file);
        } catch (
        Docx4JException e) {
            throw new DocAsCodeException(
                    String.format("Unable to update tables of %s",
                            file.getAbsolutePath())
                    ,e);

        }
    }
}