Replacing variables in a word document template with java

前端 未结 3 1632
深忆病人
深忆病人 2020-12-12 22:53

I want to load a template word document to add content to and save as new document. I\'m working on .doc file.

After a long research I only found solutions for docx

3条回答
  •  攒了一身酷
    2020-12-12 23:38

    Recently I had to solve the same problem but with a .docx document. And trying the approach above resulted as the following error (As reported in this post):

    org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)

    Finally, I had to change the code as follow (in my case the .docx file is inside the resource folder):

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    
    public class XWPFTest {
    
        public static void main(String[] args) throws URISyntaxException, IOException {
            String resourcePath = "template.docx";
            Path templatePath = Paths.get(XWPFTest.class.getClassLoader().getResource(resourcePath).toURI());
            XWPFDocument doc =  new XWPFDocument(Files.newInputStream(templatePath));
            doc = replaceTextFor(doc, "UNIQUE_VAR", "MyValue1");
            saveWord("C:\\document.docx", doc);
        }
    
        private static XWPFDocument replaceTextFor(XWPFDocument doc, String findText, String replaceText){
            doc.getParagraphs().forEach(p ->{
                p.getRuns().forEach(run -> {
                    String text = run.text();
                    if(text.contains(findText)) {
                        run.setText(text.replace(findText, replaceText), 0);
                    } 
                });
            });
    
            return doc;
        }
    
        private static void saveWord(String filePath, XWPFDocument doc) throws FileNotFoundException, IOException{
            FileOutputStream out = null;
            try{
                out = new FileOutputStream(filePath);
                doc.write(out);
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            finally{
                out.close();
            }
        }
    
    }
    

    P.S. I had to remove the $ because in .docx are managed are separate runs so I had to opt for the approach of a unique var name. I needed the following Apache POI dependencies:

    
        org.apache.poi
        poi
        3.17
    
    
        org.apache.poi
        poi-ooxml
        3.17
    
    
        org.apache.poi
        poi-scratchpad
        3.17
    
    

提交回复
热议问题