When you insert content as an object, you create a dynamic link between the content that you insert and the content that was created in another Microsoft Office program. Unlike when you paste content (such as by pressing CTRL+V), when you insert it as a linked or embedded object, you can work with it in the original program.
For example, if you insert worksheet cells into the document as an Excel object, Microsoft Office Word runs Excel when you double-click the cells, and you can use Excel commands to work with the worksheet content.
Understand the differences between linked objects and embedded objects
The main differences between linked objects and embedded objects are where the data is stored and how you update the data after you place it in the Word file.
You place either a link to the object or a copy of the object in the document. You can insert objects this way from any program that supports the technology of linking and embedding objects (object linking and embedding, or OLE).
For example, a monthly status report may contain information that is separately maintained in an Excel worksheet. If you link the report to the worksheet, the data in the report can be updated whenever the source file is updated. If you embed the worksheet in the report, your report contains a static copy of the data.
1. Embedded object
2. Linked object
3. Source file
Linked objects
When an object is linked, information can be updated if the source file is modified. Linked data is stored in the source file. The Word file, or destination file, stores only the location of the source file, and it displays a representation of the linked data. Use linked objects if file size is a consideration.
Linking is also useful when you want to include information that is maintained independently, such as data collected by a different department, and when you need to keep that information up-to-date in a Word document.
Embedded objects
When you embed an Excel object, information in the Word file doesn’t change if you modify the source Excel file. Embedded objects become part of the Word file and, after they are inserted, they are no longer part of the source file.
Because the information is totally contained in one Word document, embedding is useful when you don’t want the information to reflect changes in the source file, or when you don’t want the document recipients to be concerned with updating the linked information.
Need more help?
Want more options?
Explore subscription benefits, browse training courses, learn how to secure your device, and more.
Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.
Word OLE (Object Linking and Embedding) object is used to make contents, created in one program, available in Word document. For example, users can insert an Excel worksheet in a Word document.
Both Linked object and Embedded object can be used between Word and other programs. The data of Embedded objects is saved in Word and should be updated manually, while data of Linked object remains as separate file and will be updated when source data is changed.
Spire.Doc for .NET , a professional component to manipulate Word documents with .NET, enables users to insert OLE objects in Word by using C#/VB.NET. This guide will show you how to insert one kind of OLE objects, Linked objects (an Excel Worksheet) in Word.
Users can invoke paragraph.AppendOleObject(string pathToFile, olePicture, OleObjectType) method to insert OLE objects in Word. The parameters, olePicture and OleObjectType are properties of DocOleObject class which is provided by Spire.Doc for .NET.
The following steps present details to insert OLE Objects in Word. The following demonstrate a document before insert the OLE Object into Word, and at the bottom, you can find the result screenshot after inserting. Before starting with the steps, download and install Spire.Doc for .NET on system.
Code Detail:
Step 1: Define a GetExcelImage(string ExcelFile) method to get olePicture. Actually, the olePicture is image of data information in original Excel worksheet. The image is generated from Excel through Spire.XLS for .NET that will be shown in documents after inserting OLE object in Word. Double click this picture and you can get the original worksheet.
[C#]
private static Image GetExcelImage(String ExcelFile) { //Load Excel File Workbook workbook = new Workbook(); workbook.LoadFromFile(ExcelFile); Worksheet sheet = workbook.Worksheets[0]; //Set Image Range int lastRow = sheet.LastRow; int lastColumn = sheet.LastColumn; return workbook.Worksheets[0].SaveToImage(1, 1, lastRow, lastColumn); }
[VB.NET]
Private Shared Function GetExcelImage(ByVal ExcelFile As String) As Image 'Load Excel File Dim workbook As New Workbook() workbook.LoadFromFile(ExcelFile) Dim sheet As Worksheet = workbook.Worksheets(0) 'Set Image Range Dim lastRow As Integer = sheet.LastRow Dim lastColumn As Integer = sheet.LastColumn Return workbook.Worksheets(0).SaveToImage(1, 1, lastRow, lastColumn) End Function
Step 2: Insert OLE object. After adding paragraph in Word document, declare a new DocPicture. Then, use GetExcelImage(string ExcelFile) method which is defined in step 1 to get image source and then use picture.LoadImage(Image) method to load this image. Finally, insert OLE objects.
[C#]
para = mysec.AddParagraph(); DocPicture picture = new DocPicture(mydoc); Image image = GetExcelImage(@"E:workDocumentsExcelFilesCustomers.xlsx");//Get Image Source picture.LoadImage(image);//Load Image DocOleObject obj = para.AppendOleObject(@"E:workDocumentsExcelFilesCustomers.xlsx", picture, Spire.Doc.Documents.OleObjectType.ExcelWorksheet);
[VB.NET]
'Insert OLE Object para = mysec.AddParagraph() Dim picture As New DocPicture(mydoc) Dim image As Image = GetExcelImage("E:workDocumentsExcelFilesCustomers.xlsx") 'Get Image Source picture.LoadImage(image) 'Load Image Dim obj As DocOleObject = para.AppendOleObject("E:workDocumentsExcelFilesCustomers.xlsx", picture, Spire.Doc.Documents.OleObjectType.ExcelWorksheet)
After this coding, you can run this application and a result will show up as below:
Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.
-
#1
Hi,
I have an OLE object embedded in my Word document (in this case, an object
of type «MyCompany.TemperatureMap»). I embed the object as follows:
theNewShape = m_LoadedDocument.InlineShapes.AddOLEObject( _
ClassType:=»MyCompany.TemperatureMap», _
FileName:=CType(thePathToMyTemperatureMap, Object), _
LinkToFile:=False, _
DisplayAsIcon:=False, _
Range:=theShape.Range)
This object implements the IOleItemContainer interface. This interface can
return to me «tools» which have an X, Y position in the map and a
temperature value. These tools support IDataObject. It is possible in Word
to «copy» one of these tools from an active MyCompany.TemperatureMap and
«paste link» into the document, such that when the tool is moved around on
the map, the tool value in the document is automatically updated (its «hot»
linked).
The trouble I’m having is doing this without user intervention. Does anyone
know how I can embed a «link» programmatically?
Thanks for any help you can give me on this,
Robin
Задание: Задание выполнить в режиме Разметка страницы команды Вид главного меню Word.
I. Оформить таблицу 1
Расходы фирмы «Asus» за 1-ый квартал 2008 г. (тыс. руб.)
Расходы фирмы «Asus» за 1-ый квартал 2008 г. (тыс. руб.) |
||||
Код |
Категория |
Январь |
Февраль |
Март |
2820 |
Фонд заработной платы |
31904 |
31904 |
31904 |
2650 |
Налоги |
3828 |
3828 |
3828 |
3092 |
Выплаты по контрактам |
6500 |
6500 |
6500 |
2830 |
Премии |
834 |
450 |
1200 |
2940 |
Доступ в ИНТЕРНЕТ |
125 |
125 |
125 |
2941 |
Командировки |
1083 |
975 |
1400 |
2940 |
Телефон |
321 |
321 |
321 |
Всего по месяцам |
44595 |
44103 |
45278 |
II. Продемонстрировать технологию OLE
Действия:
Для выполнения задания следует скопировать первую таблицу приложение Ms Excel. Для этого нужно выделить первую таблицу, затем нажать кнопку Копировать.
В результате копия таблиц окажется в буфере обмена. Свернуть текущее окно Word. Нажать кнопку Пуск. Выбрать Создать Документ Microsoft Office, затем в появившемся окне щелкнуть по ярлыку Еxcel. Откроется новый рабочий лист электронной таблицы Excel. Установите курсор в ячейку с адресом А1. Щелкнуть по кнопке Вставить,
Таблица будет скопирована на рабочий лист Excel.
Чтобы поместить в Word данные, связанные с рабочим листом Ехсel необходимо выполнить следующие действия:
- Открыть рабочую книгу Excel и рабочий лист, содержащий нужные данные;
- Выделить таблицу рабочего листа Excel. Выбрать команду Правка,
Копировать; - Свернуть текущее окно рабочего листа Excel и распахнуть окно
документа Word; - Установить курсор в нижней части листа (после первой таблицы);
- Выбрать команду Правка, Специальная вставка. При этом будет открыто окно Специальная вставка ;
- Выбрать переключатель «Связать»;
В диалоговом окне Специальная вставка в списке «Как» (As) выбрать строку «Обьект: лист Microsoft Excel»;
- Нажать кнопку ОК, Данные из рабочей книги Ms Ехсеl будут помещены в документ Word как рисунок.
Изменить эти данные непосредственно в Word нельзя. Для того чтобы внести изменения в исходные данные и убедиться, что документ Word должным образом реагирует на внесенные изменения, нужно выполнить следующее:
- Открыть исходную рабочую книгу Excel и внести изменения в скопированной ранее таблице по образцу;
Расходы фирмы «Asus» за 2-ый квартал 2008 г. (тыс. руб.)
Код
Категория
Апрель
Май
Июнь
2820
Фонд заработной платы
34900
34900
34900
2650
Налоги
4188
4188
4188
3092
Выплаты по контрактам
6500
6500
6500
2830
Премии
834
450
1200
2940
Доступ в ИНТЕРНЕТ
125
125
125
2941
Командировки
1083
975
1400
2940
Телефон
321
321
321
Всего по месяцам
- Для вычисления в Excel общей суммы расходов за Апрель следует установить курсор в ячейку C9 и нажать на значок ∑ Автосуммы, затем нажать клавишу «Enter».
По аналогии, вычислить общую сумму расходов за Май и Июнь месяцы;
-
Закончив внесение изменений, нажать клавишу «Enter», для того чтобы выполнить обновление данных. При этом, соответствующие данные в документе Word также будут обновлены;
Переключится в Ms Word, для того чтобы увидеть изменения.
Расходы фирмы «Asus» за 2-ый квартал 2008 г. (тыс. руб.)
Код
Категория
Апрель
Май
Июнь
2820
Фонд заработной платы
34900
34900
34900
2650
Налоги
4188
4188
4188
3092
Выплаты по контрактам
6500
6500
6500
2830
Премии
834
450
1200
2940
Доступ в ИНТЕРНЕТ
125
125
125
2941
Командировки
1083
975
1400
2940
Телефон
321
321
321
Всего по месяцам
47951
47459
48634
OLE (Object Linking and Embedding) technology allows you to insert data (spreadsheets, images, presentations, charts, equations, etc.) from external applications into your document. Use the Word Processing Document API to load, add, extract, or remove OLE objects. You can print documents with OLE objects and export them to PDF.
Important
The Word Processing Document API does not support OLE objects in OpenDocument Text (.odt) and encrypted DOC files.
Access OLE Objects
OLE objects are stored in the SubDocument.Shapes collection. Use the ShapeCollection.Item property to return an OLE object from the collection. The Shape.Type property helps you distinguish between different drawing object types in the document.
The DrawingObject.OleFormat property returns the OLE object’s characteristics.
Property | Description |
---|---|
OleFormat.InsertType | Indicates whether the OLE object is embedded in the document or linked to an external file. |
OleFormat.ObjectRepresentation | Indicates how the OLE object is displayed in the document (as an image or an icon). |
OleFormat.ProgId | Returns the content type associated with the OLE object. |
OleFormat.SourceFileName | Returns a path to the source file associated with the linked OLE object. |
OleFormat.AutoUpdate | Specifies whether to automatically update the OLE object with data from the linked file. |
OleFormat.IsLocked | Specifies whether the linked OLE object can be updated. |
OleFormat.OlePackage | Returns properties for the OLE object of the Package type. |
The following example retrieves all linked objects from the document:
- C#
- VB.NET
using System.Linq;
// ...
Document document = wordProcessor.Document;
List<DrawingObject> linkedObjects = document.Shapes.Flatten()
.Where(x => x.Type == ShapeType.OleObject &&
x.OleFormat.InsertType == OleInsertType.Linked)
.ToList();
Insert OLE Objects
Linked Objects
Use the ShapeCollection.InsertOleObject method overload with the fileName parameter to create an OLE object that stores a link to a specified file. You can use constant fields of the OleObjectType class to specify the file type. The OLE object is displayed in the document as an image.
- C#
- VB.NET
Document document = wordProcessor.Document;
// Insert an OLE object. Link it to an Excel worksheet.
Shape oleObject = document.Shapes.InsertOleObject(document.CreatePosition(1780), @"D:ExcelWorkbook.xlsx",
OleObjectType.ExcelWorksheet, DocumentImageSource.FromFile(@"ImagesSpreadsheet.png"));
// Specify the object position on the page.
oleObject.RelativeHorizontalPosition = ShapeRelativeHorizontalPosition.Column;
oleObject.RelativeVerticalPosition = ShapeRelativeVerticalPosition.Paragraph;
oleObject.Offset = new PointF(0, 0);
// Specify how text wraps around the object.
oleObject.TextWrapping = TextWrappingType.TopAndBottom;
Open the document in Microsoft® Word® and double-click the image to open the file associated with the OLE object.
Embedded Objects
Use the ShapeCollection.InsertOleObject method overload with the stream parameter to embed data from an external file in the document. You can use constant fields of the OleObjectType class to specify the content type. The OLE object is displayed in the document as an image.
- C#
- VB.NET
Document document = wordProcessor.Document;
// Embed data from an Excel worksheet in the document.
using (Stream excelStream = File.Open(@"D:ExcelWorkbook.xlsx", FileMode.Open))
{
Shape oleObject = document.Shapes.InsertOleObject(document.CreatePosition(1780), excelStream,
OleObjectType.ExcelWorksheet, DocumentImageSource.FromFile(@"ImagesSpreadsheet.png"));
// Specify the object position on the page.
oleObject.RelativeHorizontalPosition = ShapeRelativeHorizontalPosition.Column;
oleObject.RelativeVerticalPosition = ShapeRelativeVerticalPosition.Paragraph;
oleObject.Offset = new PointF(0, 0);
// Specify how text wraps around the object.
oleObject.TextWrapping = TextWrappingType.TopAndBottom;
}
Open the document in Microsoft® Word® and double-click the OLE object to modify the embedded data.
Display OLE Objects as Icons
Use the ShapeCollection.InsertOleObjectAsIcon method overloads to insert OLE objects as icons.
- C#
- VB.NET
Document document = wordProcessor.Document;
// Insert an OLE object. Link it to an Excel worksheet.
// The OLE object is displayed in the document as an icon.
Shape oleObject = document.Shapes.InsertOleObjectAsIcon(document.CreatePosition(1780), @"D:ExcelWorkbook.xlsx",
OleObjectType.ExcelWorksheet, DocumentImageSource.FromFile(@"ImagesExcel.ico"));
// Specify the object position on the page.
oleObject.RelativeHorizontalPosition = ShapeRelativeHorizontalPosition.Column;
oleObject.RelativeVerticalPosition = ShapeRelativeVerticalPosition.Paragraph;
oleObject.Offset = new PointF(0, 0);
// Specify how text wraps around the object.
oleObject.TextWrapping = TextWrappingType.TopAndBottom;
Open the document in Microsoft® Word® and double-click the icon to open the file associated with the OLE object.
Group OLE Objects
Call the ShapeCollection.InsertGroup method to create a shape group. The Shape.GroupItems property returns a collection of group elements. Use the collection’s AddOleObject and AddOleObjectAsIcon methods to add OLE objects to the group.
The following example groups two OLE objects:
- C#
- VB.NET
Document document = wordProcessor.Document;
// Set measurement unit to inches.
document.Unit = DevExpress.Office.DocumentUnit.Inch;
// Insert a shape group.
Shape group = document.Shapes.InsertGroup(document.Range.Start);
// Specify the group position relative to the left and top edges of the page.
group.Offset = new PointF(1f, 6f);
// Access the collection of group items.
var groupItems = group.GroupItems;
// Add the first OLE object to the group.
groupItems.AddOleObjectAsIcon(@"D:ExcelWorkbook.xlsx", OleObjectType.ExcelWorksheet,
DocumentImageSource.FromFile(@"ImagesExcel.ico"), new PointF(0f, 0f));
// Add the second OLE object to the group.
groupItems.AddOleObjectAsIcon(@"D:PowerPointPresentation.pptx", OleObjectType.PowerPointPresentation,
DocumentImageSource.FromFile(@"ImagesPowerPoint.ico"), new PointF(1.5f, 0f));
Change OLE Object Display Style
Use the OleFormat.ChangeRepresentation method to change how an existing OLE object is displayed in the document.
- C#
- VB.NET
Document document = wordProcessor.Document;
// Insert an OLE object. Link it to an Excel worksheet.
// The OLE object is displayed in the document as an image.
Shape oleObject = document.Shapes.InsertOleObject(document.CreatePosition(1780), @"D:ExcelWorkbook.xlsx",
OleObjectType.ExcelWorksheet, DocumentImageSource.FromFile(@"ImagesSpreadsheet.png"));
// Display the OLE object as an icon.
oleObject.OleFormat.ChangeRepresentation(OleObjectRepresentationType.Icon,
DocumentImageSource.FromFile(@"ImagesExcel.ico"));
Retrieve Embedded Data
Use the OleFormat.GetRawData method to retrieve an embedded OLE object’s data.
The following example loads spreadsheet data from a Word document into the Spreadsheet Document API component. You can modify and save this data to a file.
Important
You need a license to the DevExpress Office File API or DevExpress Universal Subscription to use this example in production code. Refer to the following page for pricing information: DevExpress Subscriptions.
- C#
- VB.NET
using System.Linq;
using DevExpress.XtraRichEdit.API.Native;
// Add references to DevExpress.Docs.dll
// and DevExpress.Spreadsheet.Core.dll.
using DevExpress.Spreadsheet;
// ...
Document document = wordProcessor.Document;
// Obtain an OLE object that stores spreadsheet data.
DevExpress.XtraRichEdit.API.Native.Shape embeddedObject = document.Shapes.FirstOrDefault(
x => x.Type == DevExpress.XtraRichEdit.API.Native.ShapeType.OleObject &&
x.OleFormat.InsertType == OleInsertType.Embedded &&
x.OleFormat.ProgId == OleObjectType.ExcelWorksheet);
if (embeddedObject != null)
{
// Retrieve data from the OLE object.
byte[] spreadsheetData = embeddedObject.OleFormat.GetRawData();
// Create a Workbook instance.
using (Workbook workbook = new Workbook()) {
// Load data into the workbook.
workbook.LoadDocument(spreadsheetData);
// Modify data.
// ...
// Save the document.
workbook.SaveDocument("ExcelDocument.xlsx", DevExpress.Spreadsheet.DocumentFormat.Xlsx);
}
}
Save Data to a File
Use the OleFormat.SaveAs method to save an embedded OLE object’s data to a file.
- C#
- VB.NET
using System.Linq;
using DevExpress.XtraRichEdit.API.Native;
// ...
Document document = wordProcessor.Document;
// Obtain an OLE object that stores spreadsheet data.
DevExpress.XtraRichEdit.API.Native.Shape embeddedObject = document.Shapes.FirstOrDefault(
x => x.Type == DevExpress.XtraRichEdit.API.Native.ShapeType.OleObject &&
x.OleFormat.InsertType == OleInsertType.Embedded &&
x.OleFormat.ProgId == OleObjectType.ExcelWorksheet);
if (embeddedObject != null)
{
// Save the OLE object's data as an XLSX document.
embeddedObject.OleFormat.SaveAs("ExcelDocument.xlsx");
}
Remove OLE Objects
Use one of the following methods to remove an OLE object from the document:
-
ShapeCollection.Remove — removes a specific object from the collection;
-
ShapeCollection.RemoveAt — removes an object with the specified index from the collection;
-
ShapeCollection.Clear — clears the shape collection.
The following example removes all OLE objects from the collection:
- C#
- VB.NET
Document document = wordProcessor.Document;
ShapeCollection shapes = document.Shapes;
for (int i = shapes.Count - 1; i >= 0; i--)
{
if (shapes[i].Type == ShapeType.OleObject)
shapes.Remove(shapes[i]);
}
See Also
I am trying to replicate the following method in C# Word interop (NetOffice)
Selection.PasteSpecial Link:=True, DataType:=wdPasteMetafilePicture, _
Placement:=wdInLine, DisplayAsIcon:=False
I am saying «replicate» since I don’t want to actually use the `PasteSpecial` method, since I need to update many `field`s of type `link` in one go, and don’t like to communicate with excel by relying on copy and paste.
I already have the following code that does mostly what I want but has some issues that I am not able to overcome.
Selection.InlineShapes.AddOLEObject («Excel.Sheet.12″, fileName + $»!{label}», true)
This method fails with an error message
> Word is unable to create a link to the object you specified. Please insert the object directly into your file without creating a link
I am only getting this error message, if and only if I use a network drive or unc path with a label.
eg.
T:TestFile.xlsx!Sheet1!TestRange
T:TestFile.xlsx!Sheet1!R1C1:R2C2
//notice that T is a network drive and not a local drive
\TestShareTestFile.xlsx!Sheet1!TestRange
\TestShareTestFile.xlsx!Sheet1!R1C1:R2C2
If I dont use the label
eg.
T:TestFile.xlsx
T:TestFile.xlsx
//notice that T is a network drive and not a local drive
\TestShareTestFile.xlsx
\TestShareTestFile.xlsx
or a local drive eg. C: (with or without label)
C:TestFile.xlsx
C:TestFile.xlsx
C:TestFile.xlsx!Sheet1!TestRange
C:TestFile.xlsx!Sheet1!R1C1:R2C2
everything works fine.
So, only the combination network drive or unc + a label produces that error message.
I thought, okay no problem I already know how to change the path and label of the produced `field` and wrote the following code to include the label in a second step.
var inlineShape = Selection.InlineShapes.AddOLEObject(«Excel.Sheet.12», fileName, true);
field = inlineShape.Field;
if (!string.IsNullOrEmpty(label))
{
var fieldCode = field.Code.Text;
//replace the produced empty label «» with the label I desire eg. «Sheet1!R1C1:R2C2»
fieldCode = fieldCode.Replace(» «» «, $» «{label}»»);
//write the updated fieldcode back to the field
field.Code.Text = fieldCode;
//update the field
field.Update();
}
BUT this solution, changes the underlying format of the image from WMF (Windows Meta File) to EMF (Enhanced Meta File), but I need it to be stored in the WMF format, since `Office 2010` doesn’t render the correct.
To get the underlying file, I rename my `docx` to `zip` and extract it to look into the `wordmedia` directory.
`PasteSpecial` doesn’t throw that error, and produces that desired WMF format, but I can’t seem to 100% replicate the routine that happens while `PasteSpecial`.
As I side note, I don’t want to have `png` or `bmp` either, since those are generated with a blur around the font, so the best result delivers `wmf` for `Office 2010`.
For `Office 2013` and higher, I am using the following code to get `emf` right from the start and don’t face issue about network drive/unc + label error.
var field = range.Fields.Add(range, WdEnums.WdFieldType.wdFieldLink);
field.LinkFormat.SourceFullName = fileName + $»!{label}»;
You can also find the issue here:
https://stackoverflow.com/questions/60565712