2016-08-04 137 views
-1

有人可以告诉我如何使用java将图片复制到word文档。我试过了一段代码,但是我一直收到一个错误,说文档内容有误。请帮助。提前感谢一堆!将图片复制到word文档

+1

你检查此链接[http://stackoverflow.com/questions/17745466/insert-picture-in-word-document](http://stackoverflow.com/questions/17745466/insert-picture -in字文档)? –

+0

是的,我看到了这个代码。而且我在2010年得到了完全相同的错误。“文档文件无法打开,因为内容存在问题。”我没有看到在这个问题的解决方案的意见:( –

回答

1

原则上这很简单,因为您可以简单地使用XWPFRun.addPicture将图片添加到XWPFRun。

import java.io.FileOutputStream; 
import java.io.FileInputStream; 
import java.io.IOException; 

import org.apache.poi.util.Units; 

import org.apache.poi.xwpf.usermodel.*; 

public class CreateWordWithImage { 

public static void main(String[] args) throws Exception { 

    XWPFDocument doc= new XWPFDocument(); 

    XWPFParagraph paragraph = doc.createParagraph(); 
    XWPFRun run=paragraph.createRun(); 
    run.setText("The Body:"); 

    paragraph = doc.createParagraph(); 
    run=paragraph.createRun(); 
    run.setText("Lorem ipsum...."); 

    run = paragraph.createRun(); 
    String imgFile="Koala.png"; 
    XWPFPicture picture = run.addPicture(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(100), Units.toEMU(100)); 

    run = paragraph.createRun(); 
    run.setText("...Lorem ipsum...."); 

    paragraph = doc.createParagraph(); 
    run=paragraph.createRun(); 
    run.setText("Lorem ipsum...."); 

    doc.write(new FileOutputStream("test.docx")); 

} 
} 
+0

非常感谢你亚历克斯..此代码在Windows 2013中完美工作。但我在2010年出现错误。错误是文档文件无法打开因为内容有问题 –

+0

您使用的是什么apache poi版本?我的版本是poi-3.14。适用于在Word 2007,Word 2016,Openoffice 4.1.2 Writer和Libreoffice 5.1.4 Writer中打开。我很肯定不应该有问题,也许你正在使用的图片是问题?尝试另一种方法?尝试在Word 2010 GUI中手动插入图片? –

+0

我正在使用3.10。和3.14。在2010年试用了它。没有工作..我可以手动插入图片,但!! !!我做了一些研究,并认为也许我们可能需要创建自己的xwpf文档。不知道我是否正确地分享我发现的东西。 –

相关问题