poi对word2003或者2007的图片读取和写入操作

来源:互联网 发布:java mvc框架实例 编辑:程序博客网 时间:2024/05/18 01:23

poi对word2003或者2007的图片读取和写入操作

1.word2003版doc读取某个标签所在位置的值或者图片

HWPFDocument docDocument = new HWPFDocument(is);org.apache.poi.hwpf.usermodel.Bookmarks bookmarks =     docDocument.getBookmarks();PicturesTable picturesTable = docDocument.getPicturesTable();System.out.println("图片数量: " +     picturesTable.getAllPictures().size());List<Picture> list = picturesTable.getAllPictures();Map<String, String> result = new HashMap<String, String>();int count = bookmarks.getBookmarksCount();for (int i = 0; i < count; i++) {    Range range = new Range(bookmarks.getBookmark(i).getStart(),  bookmarks.getBookmark(i).getEnd(), docDocument);    CharacterRun cr = range.getCharacterRun(0);    if (picturesTable.hasPicture(cr)) {        Picture pic = picturesTable.extractPicture(cr, true); //获得的图片    }else{ //如果标签是文本的话,取出标签所在位置的值        if (range.text().equals("")) {                     result.put(bookmarks.getBookmark(i).getName(), null);        } else {                   result.put(bookmarks.getBookmark(i).getName(), "\"" + range.text() + "\"");        }    }

docx文件图片的写入某个特点标签位置;对图片写入poi jar中的方法存在错误,要自己继承XWPFDocument,重写写入图片的方法

for (BookMark item : bookMarks.getBookmarkList()) {    File pic = new File("/Users/ycc/Desktop/13d0.png");    FileInputStream is = new FileInputStream(pic);    if (item.getBookmarkName().equals("logo2")) {        String ind = docxDocument.addPictureData(is, docxDocument.PICTURE_TYPE_PNG);//不同版本的poi jar中没有addPicutre(is,docxDocument.PICTURE_TYPE_PNG);返回int。createPicture函数的第一个值可以用docxDocument.getAllPictures().size()-1代替        XWPFParagraph pargraph = item.getContainerTableRow().getCell(0).addParagraph();//图片标签一定要在某个表格的单元格中    if (docxDocument.getAllPictures() == null || docxDocument.getAllPictures().isEmpty()) {    docxDocument.createPicture(0, 100, 150, pargraph); //100是宽 ,150高    } else { docxDocument.createPicture(docxDocument.getAllPictures().size() - 1, 100, 150, pargraph);}}System.out.println("测试一下: " + docxDocument.getAllPictures().size());FileOutputStream fos = new FileOutputStream("/Users/ycc/Desktop/testcopy.docx");docxDocument.write(fos);fos.flush();fos.close();

研究很久,并发现java poi不能处理word2003版的图片插入问题,希望大家能提出好的建议和意见

后面有读取word模版文件,生成表单,生成文件和将生成的文件还原成表单进行修改的方法,包括下拉框的处理。

1.有人会问为什么不直接修改word文档,因为一旦在文档中设置标签之后,当对某个标签位置的内容进行修改后,标签就不见了,因此需要通过代码来对文件进行修改。
2.java poi对word的支持并不好,尤其是对word2003版的支持更少,所以如果需要对word进行处理,可以考虑pageOffice。
3.对于标签的理解,java poi中其实是获得不到所谓的标签的,标签其实也是单元格中的数据,具体的看附件中的bookmark和bookmarks两个类。
http://download.csdn.net/detail/u011376686/9615949 相关代码下载地址

0 0
原创粉丝点击