如何用poi修改word中的内容

来源:互联网 发布:php开发是什么 编辑:程序博客网 时间:2024/04/28 03:29

    近期在做一个用java修改word内容的功能,在网上搜索结合自己理解写了一段代码,放在博客中以供大家参考。但word2003修改时有时会有乱码,表格样式也会发生改变,暂时还未解决。

package wordTest;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.poi.POIXMLDocument;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.model.FieldsDocumentPart;import org.apache.poi.hwpf.usermodel.Field;import org.apache.poi.hwpf.usermodel.Fields;import org.apache.poi.hwpf.usermodel.Range;import org.apache.poi.openxml4j.opc.OPCPackage;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.apache.poi.xwpf.usermodel.XWPFParagraph;import org.apache.poi.xwpf.usermodel.XWPFRun;public class ReadAndWriteDoc {    /**     * 实现对word读取和修改操作(word2003.doc)     */    public static void readwriteWord1(String filePath, Map<String,String> map){        //读取word模板//        String fileDir = new File(base.getFile(),"http://www.cnblogs.com/http://www.cnblogs.com/../doc/").getCanonicalPath();        FileInputStream in = null;        try {            in = new FileInputStream(new File(filePath));        } catch (FileNotFoundException e1) {            e1.printStackTrace();        }        HWPFDocument hdt = null;        try {            hdt = new HWPFDocument(in);        } catch (IOException e1) {            e1.printStackTrace();        }        Fields fields = hdt.getFields();        Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();        while(it.hasNext()){            System.out.println(it.next().getType());        }        //读取word文本内容        Range range = hdt.getRange();        System.out.println(range.text());        //替换文本内容        for (Map.Entry<String,String> entry: map.entrySet()) {            range.replaceText(entry.getKey() ,entry.getValue());        }        ByteArrayOutputStream ostream = new ByteArrayOutputStream();        String fileName = System.currentTimeMillis()+filePath.substring(filePath.lastIndexOf("/")+1, filePath.length());        FileOutputStream out = null;        try {            out = new FileOutputStream("D:\\My Test\\word\\out\\"+fileName,true);        } catch (FileNotFoundException e) {            e.printStackTrace();        }        try {            hdt.write(ostream);        } catch (IOException e) {            e.printStackTrace();        }        //输出字节流        try {            out.write(ostream.toByteArray());        } catch (IOException e) {            e.printStackTrace();        }        try {            out.close();        } catch (IOException e) {            e.printStackTrace();        }        try {            ostream.close();        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 实现对word读取和修改操作(word2007.docx)     */    public static void readwriteWord2(String filePath, Map<String,String> map){        try {            OPCPackage pack = POIXMLDocument.openPackage(filePath);            XWPFDocument doc = new XWPFDocument(pack);            List<XWPFParagraph> paragraphs = doc.getParagraphs();            System.out.println(paragraphs.size());            for (XWPFParagraph tmp : paragraphs) {                System.out.println(tmp.getParagraphText());                List<XWPFRun> runs = tmp.getRuns();                for (XWPFRun aa : runs) {                    System.out.println("XWPFRun-Text:" + aa.getText(0));                    for (Map.Entry<String,String> entry: map.entrySet()) {                        if (aa.getText(0) != null && aa.getText(0).contains(entry.getKey())) {                            aa.setText(entry.getValue(), 0);                        }                    }                }            }            String fileName = System.currentTimeMillis()+filePath.substring(filePath.lastIndexOf("/")+1, filePath.length());            FileOutputStream fos = new FileOutputStream("D:\\My Test\\word\\out\\"+fileName,true);            doc.write(fos);            fos.flush();            fos.close();        } catch (Exception e) {            e.printStackTrace();        }    }    public static void main(String[] args) {        String filePath = System.getProperty("user.dir")+"/resource/test.doc";        Map<String,String> map = new HashMap<String, String>();        map.put("URL说明", "hello, world!");        map.put("请求", "hello, world!");        readwriteWord1(filePath, map);    }}