Spire.XLS for Java支持将Word, Excel, PowerPoint幻灯片和PDF文档以OLE 对象嵌入到Excel工作表。本文将详细介绍如何使用Spire.Xls将Word文档作为OLE对象插入到Excel工作表。
import com.spire.xls.*;
import com.spire.xls.core.IOleObject;
import com.spire.doc.*;
import com.spire.doc.documents.ImageType;
import java.awt.image.BufferedImage;
public class insertOLEObjects {
public static void main(String[] args) {
String docFile = "Sample.docx";
String outputFile = "output/insertOLEObjects_result.xlsx";
//加载Excel文档
Workbook workbook = new Workbook();
workbook.loadFromFile("Sample.xlsx");
//获取第一张工作表
Worksheet worksheet = workbook.getWorksheets().get(0);
//生成图片
BufferedImage image = GenerateImage(docFile);
//插入OLE对象
IOleObject oleObject = worksheet.getOleObjects().add(docFile, image, OleLinkType.Embed);
oleObject.setLocation(worksheet.getCellRange("B4"));
oleObject.setObjectType(OleObjectType.ExcelWorksheet);
//保持文档
workbook.saveToFile(outputFile, ExcelVersion.Version2010);
}
private static BufferedImage GenerateImage(String fileName) {
//加载Word文档
Document document = new Document();
document.loadFromFile(fileName);
//将Word文档的第一页保存为图片
BufferedImage image = document.saveToImages(0, ImageType.Bitmap);
return image;
}
}
效果图: