ole(object linking and embedding)是一种面向对象的技术,利用这一技术,可以使一个程序中创建的内容在另一个程序中可用,例如,将word文档和powerpoint幻灯片作为ole对象插入到excel工作表。实现这个功能需要下载spire.office并将相应的dll文件添加到应用程序中。本文将详细介绍如何使用spire.xls将word文档作为ole对象插入到excel工作表。
定义一个getdocimage(string docxfile) 方法获取图片,这里的图片是原始word文档中的数据信息图像,将ole对象插入到excel工作表后,这个图像将显示在excel工作表中。
c#
private static image getdocimage(string docxfile)
{
//加载word文档
document document = new document();
document.loadfromfile(docxfile);
//将word文档的第一页保存为图片
image olepicture=document.savetoimages(0, spire.doc.documents.imagetype.bitmap);
return olepicture;
}
vb.net
private shared function getdocimage(docxfile as string) as image
'加载word文档
dim document as new document()
document.loadfromfile(docxfile)
'将word文档的第一页保存为图片
dim olepicture as image = document.savetoimages(0, spire.doc.documents.imagetype.bitmap)
return olepicture
end function
调用上个步骤获取的图像,将word文档作为ole对象插入到excel工作表中。
c#
static void main(string[] args)
{
//加载excel文档
workbook workbook = new workbook();
workbook.loadfromfile("d:\\excel示例.xlsx");
//获取第一张工作表
worksheet ws = workbook.worksheets[0];
//插入ole对象
string docx = "d:\\word示例.docx";
image image = getdocimage(docx);
ioleobject oleobject = ws.oleobjects.add(docx, image, olelinktype.embed);
oleobject.location = ws.range["b4"];
oleobject.objecttype = oleobjecttype.worddocument;
//保存文档
workbook.savetofile("ole文档.xlsx", excelversion.version2013);
system.diagnostics.process.start("ole文档.xlsx");
}
vb.net
private shared sub main(args as string())
'加载excel文档
dim workbook as new workbook()
workbook.loadfromfile("d:\excel示例.xlsx")
'获取第一张工作表
dim ws as worksheet = workbook.worksheets(0)
'插入ole对象
dim docx as string = "d:\word示例.docx"
dim image as image = getdocimage(docx)
dim oleobject as ioleobject = ws.oleobjects.add(docx, image, olelinktype.embed)
oleobject.location = ws.range("b4")
oleobject.objecttype = oleobjecttype.worddocument
'保存文档
workbook.savetofile("ole文档.xlsx", excelversion.version2013)
system.diagnostics.process.start("ole文档.xlsx")
end sub