apache poi word 图片
时间: 2023-09-22 19:13:06 浏览: 42
要在 Apache POI Word 文档中插入图片,可以使用以下代码示例:
```java
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class InsertImageInWord {
public static void main(String[] args) throws IOException {
// 创建新的 Word 文档
XWPFDocument document = new XWPFDocument();
// 插入图片
String imageUrl = "https://example.com/image.png";
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
InputStream inputStream = new URL(imageUrl).openStream();
byte[] bytes = IOUtils.toByteArray(inputStream);
run.addPicture(bytes, XWPFDocument.PICTURE_TYPE_PNG, "image.png", Units.toEMU(100), Units.toEMU(100));
// 保存 Word 文档
FileOutputStream out = new FileOutputStream("image.docx");
document.write(out);
out.close();
document.close();
}
}
```
在上述代码中,我们通过 `createParagraph()` 方法创建一个新段落,然后通过 `createRun()` 方法创建一个新的运行对象。接着,我们使用 `openStream()` 方法打开图片的输入流,并使用 `IOUtils` 工具类将图片的字节流转换为字节数组。最后,我们使用 `addPicture()` 方法将图片插入到 Word 文档中。
注意,代码中的 `Units.toEMU(100)` 表示将图片的宽度和高度设置为 100 磅(1 磅 = 1/72 英寸),可以根据需要进行调整。