word 插入表格(转载*)https://*.com/questions/31835579/insert-table-into-a-word-docu

public class InsertText {
    public static void main(String[] args) throws FileNotFoundException, IOException,
            InvalidFormatException {
        try {
            FileInputStream fis = new FileInputStream("c:\\Work\\current\\***.docx");
            XWPFDocument document = new XWPFDocument(OPCPackage.open(fis));
            fis.close();
            System.out.println(document.getDocument().getBody().getPArray().length);
            List<IBodyElement> elements = document.getBodyElements();
            for (int n = 0; n < elements.size(); n++) {
                IBodyElement element = elements.get(n);
                if (element instanceof XWPFParagraph) {
                    XWPFParagraph p1 = (XWPFParagraph) element;
                    List<XWPFRun> runList = p1.getRuns();
                    StringBuilder sb = new StringBuilder();
                    for (XWPFRun run : runList)
                        sb.append(run.getText(0));
                    if (sb.toString().contains("????")) {
                        n++;
                        element = elements.get(n);
                        if (element instanceof XWPFTable) {
                            XWPFTable t = (XWPFTable) element;
                            XmlCursor cursor = t.getCTTbl().newCursor();
                            document.removeBodyElement(n);
                            XWPFParagraph p = document.insertNewParagraph(cursor);
                            XWPFRun run = p.createRun();
                            run.setText("GOAL!!!");
                            XWPFTable t2 = document.createTable(3,4);
                            XWPFTableCell cell = t2.getRow(0).getCell(0);
                            document.insertTable(n, t2);
                            cell.setText("GOAL!!!");
                            t2 = p.getBody().insertNewTbl(cursor);
                        }
                    }
                }
            }
            FileOutputStream outStream = new FileOutputStream("C:/Work/Current/**.docx");
            document.write(outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}
上一篇:SVN提交修改时出现:Checksum mismatch


下一篇:* 创始人关于如何高效编程的清单