有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用ApachePOI编辑Word模板

我想使用ApachePOI编辑Word文档模板(发票)。我加载文件并将其转换为XWPFDocument。然后我使用下面的代码来浏览这些段落

private static void updateDocument(XWPFDocument doc) throws IOException {

            List<XWPFParagraph> xwpfParagraphList = doc.getParagraphs();
            System.err.println(xwpfParagraphList.size());
            //Iterate over paragraph list and check for the replaceable text in each paragraph
            for (XWPFParagraph xwpfParagraph : xwpfParagraphList) {
                System.err.println(xwpfParagraph.getText());
                for (XWPFRun xwpfRun : xwpfParagraph.getRuns()) {
                    String docText = xwpfRun.getText(0);
                    //replacement and setting position
                    docText = docText.replace("${RestaurantName}", "My Restaurant");
                    xwpfRun.setText(docText, 0);
                }
            }

            // save the docs
            try (FileOutputStream out = new FileOutputStream("c:/Invoices/newTestDocument.docx")) {
                doc.write(out);
            }

        }

问题是代码不保存更改。我还将代码修改为

private static void updateDocument(XWPFDocument doc) throws IOException {

        List<XWPFParagraph> xwpfParagraphList = doc.getParagraphs();
        //Iterate over paragraph list and check for the replaceable text in each paragraph
        for (XWPFParagraph xwpfParagraph : xwpfParagraphList) {
            for (XWPFRun xwpfRun : xwpfParagraph.getRuns()) {
                if (!xwpfRun.getText(0).equals("")) {
                    if (xwpfRun.getText(0).equals("RestaurantName")){
                        String docText = xwpfRun.getText(0);
                        System.err.println("Text je: " + docText);
                        //replacement and setting position
                        docText = docText.replace("RestaurantName", LoginService.getLogged().getName());
                        System.out.println("Replaced " + docText);
                        xwpfRun.setText(docText, 0);
                    }

                }
            }
        }
        
        // save the docs
        try (
           write2File(doc);
        }
        catch (Exception e){
            System.err.println(e.getMessage());
        }
    }

Write2File看起来像

private static void write2File(XWPFDocument doc) throws IOException {
        String folder = "C:/Invoices/";
        String fileName = "newInvoice.docx";


        File f = new File(folder);
        if (!f.exists()) {
            f.mkdirs();

        } else {
            System.out.println("directory exists");
        }
        FileOutputStream outputStream = new FileOutputStream(new File(folder + fileName));
        doc.write(outputStream);
        doc.close();
        System.out.println("Write to file: " + folder + fileName);

}

如何修复它,或者是否有更好的方法来编辑word模板


共 (0) 个答案