码迷,mamicode.com
首页 > 编程语言 > 详细

java程序替换word2007中的图片

时间:2014-11-03 16:35:33      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:style   ar   os   java   sp   文件   数据   on   代码   

1、新建word2007文档h2do.docx;

2、QQ截图粘贴到文档,添加些文字;

3、用winrar打开(修改扩展名docx为rar或右键->打开方式->选择winrar程序),目录结构如下:

.

│  [Content_Types].xml

├─docProps

│      app.xml

│      core.xml

├─word

│  │  comments.xml

│  │  document.xml

│  │  endnotes.xml

│  │  fontTable.xml

│  │  footnotes.xml

│  │  numbering.xml

│  │  settings.xml

│  │  styles.xml

│  │  webSettings.xml

│  │

│  ├─media

│  │      image1.png

│  │      image2.png

│  │

│  ├─theme

│  │      theme1.xml

│  │

│  └─_rels

│          document.xml.rels

└─_rels

        .rels

以下代码通过java程序替换word文件中的图片image1.png

public static void main(String[] args) throws Throwable
{
    ZipInputStream  zis = new ZipInputStream (new FileInputStream ("h2do.docx") );
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("e2say.docx"));
    
    ZipEntry ze = null;
    byte[] b = new byte[1024];
    while((ze = zis.getNextEntry()) != null)
    {
        System.out.println(ze.getName() + ":" + ze.getMethod());
        ZipEntry entry = new ZipEntry(ze.getName());
        zos.putNextEntry(entry);
        
        /*将源压缩文件中每个文件写至新压缩文件*/
        InputStream is = zis;
        if(ze.getName().endsWith(".xml"))
        {
            String line = null;
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while((line = br.readLine()) != null)
            {
                //TODO:进行查证替换
                zos.write((line+"\r\n").getBytes());
            }
        }else{//非xml文件,二进制流数据
            //替换图片
            if(ze.getName().endsWith("image1.png")){
                is = new FileInputStream("temp.png");
            }

            int r = -1; 
            while((r = is.read(b)) != -1){
                zos.write(b, 0, r);
            }
            
        }
        
        if(is != zis){
            is.close();
        }
    }
    
    zos.close();
    
}


java程序替换word2007中的图片

标签:style   ar   os   java   sp   文件   数据   on   代码   

原文地址:http://my.oschina.net/h2do/blog/340221

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!