通過poi解析word(替換word中的部分內容)


解析03版(.doc)word:

HWPFDocument doc=null;              //HWPFDocument 對應03版word
        try {
             doc =new HWPFDocument(new FileInputStream("F:\\upload\\template_03.doc"));    //獲得要替換的word模板
             Range range = doc.getRange();                             //range獲取word中的內容
            for (Map.Entry<String,String> entry:replaceContent.entrySet()){          //通過一個Map來替換內容 Map中key值存被替換的內容  Map中value值存要替換的內容,最后通過一個循環實現
                range.replaceText(entry.getKey(),entry.getValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doc;

解析07(.docx) word:

XWPFDocument docx=null;
        try {
            docx=new XWPFDocument(new FileInputStream("F:\\upload\\template_07.docx"));
            List<XWPFParagraph> paragraphs = docx.getParagraphs();                //07版需先獲取段落;最后在獲取以格式分割的最小單位run
            for (XWPFParagraph paragraph:paragraphs){
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run:runs){
                    String str=run.getText(run.getTextPosition());          //獲取run中的字符串
                    for (Map.Entry<String,String> entry:replaceContent.entrySet()){
                        str=str.replace(entry.getKey(),entry.getValue());
                    }
                    run.setText(str,0);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return docx;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM