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;
}
}
效果图: