Automatización de Microsoft Word para crear un nuevo documento mediante Visual C #

Para obtener una versión de .NET de Microsoft Visual Basic de este artículo, consulte

Resumen

En este artículo paso a paso se describe cómo crear un nuevo documento en Microsoft Word mediante Automation desde Microsoft Visual C# 2005 o Microsoft Visual C# .NET.

Código de ejemplo

En el código de ejemplo de este artículo se muestra cómo hacer lo siguiente:

  • Inserte párrafos con texto y formato.
  • Examine y modifique varios intervalos dentro de un documento.
  • Inserte tablas, dé formato a las tablas y rellene las tablas con datos.
  • Agregue un gráfico.

Para crear un documento de Word con Automation desde Visual C# 2005 o Visual C# .NET, siga estos pasos:

  1. Inicie Microsoft Visual Studio 2005 o Microsoft Visual Studio .NET.

  2. En el menú Archivo, haga clic en Nuevo y, a continuación, haga clic en Proyecto. En Tipos de proyecto, haga clic en Proyectos de Visual C# y, a continuación, haga clic en Aplicación de Windows en Plantillas. Form1 se crea de forma predeterminada.

    Nota En Visual Studio 2005, haga clic en Visual C# en lugar de Proyectos de Visual C#.

  3. Agregue una referencia a la biblioteca de objetos de Microsoft Word. Para ello, siga estos pasos:

    1. On the Project menu, click Add Reference.
    2. En la pestaña COM, busque Biblioteca de objetos de Microsoft Word y haga clic en Seleccionar.

    Nota En Visual Studio 2005, no es necesario hacer clic en Seleccionar.

    Nota Microsoft Office 2003 incluye ensamblados de interoperabilidad primarios (PIA). Microsoft Office XP no incluye los PIA, pero se pueden descargar.

    1. Haga clic en Aceptar en el cuadro de diálogo Agregar referencias para aceptar las selecciones. Si se le pide que genere contenedores para las bibliotecas que seleccionó, haga clic en Sí.
  4. En el menú Ver, seleccione Cuadro de herramientas para mostrar el cuadro de herramientas y, a continuación, agregue un botón a Form1.

  5. Haga doble clic en Button1. Aparece la ventana de código del formulario.

  6. En la ventana de código, reemplace el código siguiente:

    private void button1_Click(object sender, System.EventArgs e)
    {
    }
    
    

    con:

    private void button1_Click(object sender, System.EventArgs e)
    {
    object oMissing = System.Reflection.Missing.Value;
    object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ 
    
    //Start Word and create a new document.
    Word._Application oWord;
    Word._Document oDoc;
    oWord = new Word.Application();
    oWord.Visible = true;
    oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
    ref oMissing, ref oMissing);
    
    //Insert a paragraph at the beginning of the document.
    Word.Paragraph oPara1;
    oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
    oPara1.Range.Text = "Heading 1";
    oPara1.Range.Font.Bold = 1;
    oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
    oPara1.Range.InsertParagraphAfter();
    
    //Insert a paragraph at the end of the document.
    Word.Paragraph oPara2;
    object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
    oPara2.Range.Text = "Heading 2";
    oPara2.Format.SpaceAfter = 6;
    oPara2.Range.InsertParagraphAfter();
    
    //Insert another paragraph.
    Word.Paragraph oPara3;
    oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);
    oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:";
    oPara3.Range.Font.Bold = 0;
    oPara3.Format.SpaceAfter = 24;
    oPara3.Range.InsertParagraphAfter();
    
    //Insert a 3 x 5 table, fill it with data, and make the first row
    //bold and italic.
    Word.Table oTable;
    Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
    oTable.Range.ParagraphFormat.SpaceAfter = 6;
    int r, c;
    string strText;
    for(r = 1; r <= 3; r++)
    for(c = 1; c <= 5; c++)
    {
    strText = "r" + r + "c" + c;
    oTable.Cell(r, c).Range.Text = strText;
    }
    oTable.Rows[1].Range.Font.Bold = 1;
    oTable.Rows[1].Range.Font.Italic = 1;
    
    //Add some text after the table.
    Word.Paragraph oPara4;
    oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);
    oPara4.Range.InsertParagraphBefore();
    oPara4.Range.Text = "And here's another table:";
    oPara4.Format.SpaceAfter = 24;
    oPara4.Range.InsertParagraphAfter();
    
    //Insert a 5 x 2 table, fill it with data, and change the column widths.
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);
    oTable.Range.ParagraphFormat.SpaceAfter = 6;
    for(r = 1; r <= 5; r++)
    for(c = 1; c <= 2; c++)
    {
    strText = "r" + r + "c" + c;
    oTable.Cell(r, c).Range.Text = strText;
    }
    oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2
    oTable.Columns[2].Width = oWord.InchesToPoints(3);
    
    //Keep inserting text. When you get to 7 inches from top of the
    //document, insert a hard page break.
    object oPos;
    double dPos = oWord.InchesToPoints(7);
    oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
    do
    {
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    wrdRng.ParagraphFormat.SpaceAfter = 6;
    wrdRng.InsertAfter("A line of text");
    wrdRng.InsertParagraphAfter();
    oPos = wrdRng.get_Information
                           (Word.WdInformation.wdVerticalPositionRelativeToPage);
    }
    while(dPos >= Convert.ToDouble(oPos));
    object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
    object oPageBreak = Word.WdBreakType.wdPageBreak;
    wrdRng.Collapse(ref oCollapseEnd);
    wrdRng.InsertBreak(ref oPageBreak);
    wrdRng.Collapse(ref oCollapseEnd);
    wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
    wrdRng.InsertParagraphAfter();
    
    //Insert a chart.
    Word.InlineShape oShape;
    object oClassType = "MSGraph.Chart.8";
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, 
    ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing);
    
    //Demonstrate use of late bound oChart and oChartApp objects to
    //manipulate the chart object with MSGraph.
    object oChart;
    object oChartApp;
    oChart = oShape.OLEFormat.Object;
    oChartApp = oChart.GetType().InvokeMember("Application",
    BindingFlags.GetProperty, null, oChart, null);
    
    //Change the chart type to Line.
    object[] Parameters = new Object[1];
    Parameters[0] = 4; //xlLine = 4
    oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,
    null, oChart, Parameters);
    
    //Update the chart image and quit MSGraph.
    oChartApp.GetType().InvokeMember("Update",
    BindingFlags.InvokeMethod, null, oChartApp, null);
    oChartApp.GetType().InvokeMember("Quit",
    BindingFlags.InvokeMethod, null, oChartApp, null);
    //... If desired, you can proceed from here using the Microsoft Graph 
    //Object model on the oChart and oChartApp objects to make additional
    //changes to the chart.
    
    //Set the width of the chart.
    oShape.Width = oWord.InchesToPoints(6.25f);
    oShape.Height = oWord.InchesToPoints(3.57f);
    
    //Add text after the chart.
    wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    wrdRng.InsertParagraphAfter();
    wrdRng.InsertAfter("THE END.");
    
    //Close this form.
    this.Close();
    }
    
  7. Desplácese hasta la parte superior de la ventana de código. Agregue la siguiente línea al final de la lista de directivas using:

    using Word = Microsoft.Office.Interop.Word;
    using System.Reflection;
    
  8. Presione F5 para compilar y ejecutar el programa.

  9. Haga clic en Button1 para iniciar Word Automation y crear el documento.

Una vez completado el código, examine el documento que se creó automáticamente. El documento contiene dos páginas de párrafos con formato, tablas y un gráfico.

Uso de una plantilla

Si usa Automation para compilar documentos que están todos en un formato común, puede beneficiarse de iniciar el proceso con un nuevo documento basado en una plantilla con formato previo. El uso de una plantilla con el cliente de Word Automation tiene dos ventajas significativas sobre la creación de un documento a partir de la nada:

  • Puede tener un mayor control sobre el formato y la ubicación de los objetos en los documentos.
  • Puede compilar los documentos con menos código.

Mediante el uso de una plantilla, puede ajustar la ubicación de tablas, párrafos y otros objetos dentro del documento, así como incluir el formato en esos objetos. Con Automation, puede crear un nuevo documento basado en la plantilla con código como el siguiente:

object oTemplate = "c:\\MyTemplate.dot";
oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing,
ref oMissing, ref oMissing);

En la plantilla, puede definir marcadores para que el cliente de Automation pueda rellenar texto variable en una ubicación específica del documento, como se indica a continuación:

object oBookMark = "MyBookmark";
oDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";

Otra ventaja de usar una plantilla es que puede crear y almacenar estilos de formato que desea aplicar en tiempo de ejecución, como se indica a continuación:

object oStyleName = "MyStyle";
oDoc.Bookmarks.Item(ref oBookMark).Range.set_Style(ref oStyleName);

o

object oStyleName = "MyStyle";
oWord.Selection.set_Style(ref oStyleName);

Referencias

Para obtener más información, consulte los artículos de Microsoft Knowledge Base: