Gestión de objetos OLE

Introducción

OLE (Object Linking and Embedding) es el marco de Microsoft para una tecnología de documento compuesto. En resumen, un documento compuesto es algo similar a un escritorio de visualización que puede contener objetos visuales e informativos de todo tipo: texto, calendarios, animaciones, sonido, video en movimiento, 3D, noticias actualizadas continuamente, controles, y mucho más. Cada objeto de escritorio es una entidad de programa independiente que puede interactuar con un usuario y también comunicarse con otros objetos en el escritorio.

OLE (Object Linking and Embedding) es compatible con muchos programas diferentes y se utiliza para hacer que el contenido creado en un programa esté disponible en otro. Por ejemplo, puedes insertar un documento de Microsoft Word en Microsoft Excel. Para ver qué tipos de contenido puedes insertar, haz clic en Objeto en el menú Insertar. Solo aparecen en el cuadro Tipo de objeto los programas instalados en el equipo y que admiten objetos OLE.

Inserción de objetos OLE en la hoja de cálculo

Aspose.Cells admite agregar, extraer y manipular objetos OLE en hojas de cálculo. Por esta razón, Aspose.Cells tiene la clase OleObjectCollection, utilizada para agregar un nuevo objeto OLE a la lista de colecciones. Otra clase, OleObject, representa un objeto OLE. Tiene algunos miembros importantes:

  • La propiedad ImageData especifica los datos de imagen (icono) de tipo matriz de bytes. La imagen se mostrará para mostrar el objeto OLE en la hoja de cálculo.
  • La propiedad ObjectData especifica los datos del objeto en forma de matriz de bytes. Estos datos se mostrarán en su programa relacionado cuando hagas doble clic en el ícono del objeto OLE.

El siguiente ejemplo muestra cómo agregar un objeto(s) OLE a una hoja de cálculo.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiate a new Workbook.
Workbook workbook = new Workbook();
// Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
// Define a string variable to store the image path.
string ImageUrl = dataDir + "logo.jpg";
// Get the picture into the streams.
FileStream fs = File.OpenRead(ImageUrl);
// Define a byte array.
byte[] imageData = new Byte[fs.Length];
// Obtain the picture into the array of bytes from streams.
fs.Read(imageData, 0, imageData.Length);
// Close the stream.
fs.Close();
// Get an excel file path in a variable.
string path = dataDir + "book1.xls";
// Get the file into the streams.
fs = File.OpenRead(path);
// Define an array of bytes.
byte[] objectData = new Byte[fs.Length];
// Store the file from streams.
fs.Read(objectData, 0, objectData.Length);
// Close the stream.
fs.Close();
// Add an Ole object into the worksheet with the image
// Shown in MS Excel.
sheet.OleObjects.Add(14, 3, 200, 220, imageData);
// Set embedded ole object data.
sheet.OleObjects[0].ObjectData = objectData;
// Save the excel file
workbook.Save(dataDir + "output.out.xls");

Extracción de objetos OLE en el libro de trabajo

El siguiente ejemplo muestra cómo extraer objetos OLE en un libro de trabajo. El ejemplo obtiene diferentes objetos OLE de un archivo XLS existente y guarda diferentes archivos (DOC, XLS, PPT, PDF, etc.) basándose en el tipo de formato de archivo del objeto OLE.

Después de ejecutar el código, podemos guardar diferentes archivos basados en sus respectivos tipos de formato de objetos OLE.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Open the template file.
Workbook workbook = new Workbook(dataDir + "book1.xls");
// Get the OleObject Collection in the first worksheet.
Aspose.Cells.Drawing.OleObjectCollection oles = workbook.Worksheets[0].OleObjects;
// Loop through all the oleobjects and extract each object.
// In the worksheet.
for (int i = 0; i < oles.Count; i++)
{
Aspose.Cells.Drawing.OleObject ole = oles[i];
// Specify the output filename.
string fileName = dataDir + "ole_" + i + ".";
// Specify each file format based on the oleobject format type.
switch (ole.FileFormatType)
{
case FileFormatType.Doc:
fileName += "doc";
break;
case FileFormatType.Xlsx:
fileName += "Xlsx";
break;
case FileFormatType.Ppt:
fileName += "Ppt";
break;
case FileFormatType.Pdf:
fileName += "Pdf";
break;
case FileFormatType.Unknown:
fileName += "Jpg";
break;
default:
//........
break;
}
// Save the oleobject as a new excel file if the object type is xls.
if (ole.FileFormatType == FileFormatType.Xlsx)
{
MemoryStream ms = new MemoryStream();
ms.Write(ole.ObjectData, 0, ole.ObjectData.Length);
Workbook oleBook = new Workbook(ms);
oleBook.Settings.IsHidden = false;
oleBook.Save(dataDir + "Excel_File" + i + ".out.xlsx");
}
// Create the files based on the oleobject format types.
else
{
FileStream fs = File.Create(fileName);
fs.Write(ole.ObjectData, 0, ole.ObjectData.Length);
fs.Close();
}
}

Extrayendo archivo MOL incrustado

Aspose.Cells admite la extracción de objetos de tipos poco comunes como MOL (archivo de datos moleculares que contiene información sobre átomos y enlaces). El siguiente fragmento de código muestra cómo extraer el archivo MOL incrustado y guardarlo en disco usando este archivo de Excel de muestra.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
//directories
string SourceDir = RunExamples.Get_SourceDirectory();
string outputDir = RunExamples.Get_OutputDirectory();
Workbook workbook = new Workbook(SourceDir + "EmbeddedMolSample.xlsx");
var index = 1;
foreach (Worksheet sheet in workbook.Worksheets)
{
OleObjectCollection oles = sheet.OleObjects;
foreach (var ole in oles)
{
string fileName = outputDir + "OleObject" + index + ".mol ";
FileStream fs = File.Create(fileName);
fs.Write(ole.ObjectData, 0, ole.ObjectData.Length);
fs.Close();
index++;
}
}

Temas avanzados