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