SlideShare una empresa de Scribd logo
1 de 32
Descargar para leer sin conexión
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                                                 C# and Create and Handle
                             a Word Document, by M.C. Enrique Ruiz Díaz.
                                                          All Rigths Reserved.




                  Con título y cédula profesional 5632071 en la Maestría en Ciencias de la Computación.

                                   Egresado del Instituto Tecnológico de Orizaba, Ver. (México).

                                                                                                          Página 1 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Acerca de mi.


Titulado en la Maestría en Ciencias en Ciencias de la Computación, Cédula profesional 5632071. Egresado del Instituto

Tecnológico de Orizaba, Ver., México. Antes, me Titulé en la Licenciatura en Informática, Cédula profesional 4046033. Egresado

del Instituto Tecnológico de Tuxtepec, Oax., México, distinguiéndome además, por ser el mejor promedio de mi generación con

98%.


Bien, regresando al tema de mi Título de Maestría en Ciencias de la Computación, para subrayar que ésta, requirió el desarrollo de

una TESIS. Otro aspecto muy importante, fue que durante el desarrollo de mi Maestría escribí un ARTICULO, mismo que fue

aceptado para publicación y con mi ponencia en el evento 'Primer Encuentro de Estudiantes en Ciencia de la Computación - E2C2'

ISBN-10:970-36-0404-8 e ISBN-13:978-970-36-0404-3 celebrado en el Instituto Politécnico Nacional, México, D.F. 2007.




                                                                                                                     Página 2 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                          Mi Diploma por mi Ponencia en el Instituto Politécnico Nacional, México, D.F. 2007.

                                                                                                                Página 3 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




    «Inside the great field of the Programming, I own to offer my knowledge of the Structured Programming Paradigm. This,
principally by means of the Language C. Also, I own to offer my knowledge of the Object-Oriented Paradigm. This, by means of
                                                 The Languages Java and Visual C#. Majorly».

                                                           M.C. Enrique Ruiz Díaz.
                                                                                                                Página 4 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




ÍNDICE


Acerca de mi. ............................................................................................................................................................. 2
ÍNDICE ........................................................................................................................................................................ 5
1. Lista de objetivos que logra el código C# presentado para la manipulación de un documento Word. .................. 6
2. Recursos Software utilizados. ................................................................................................................................ 6
3. Secuencia de Imágenes que prueban la creación y manipulación de un documento Word, desde código C#. ..... 7
4. Primer paso: desde el IDE Visual C# agregar una referencia al proyecto, denominada Microsoft Word xx.x
Object Library .......................................................................................................................................................... 17
5. Elementos visuales que se insertan en la aplicación. ........................................................................................... 19
6. Código C# para construir y manipular un documento Word. ............................................................................... 20




                                                                                                                                                                Página 5 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




1. Lista de objetivos que logra el código C# presentado para la manipulación de un documento Word.

   1) Asignar márgenes a la hoja, para nuestro documento, independientes de márgenes en Word indicados.
   2) Poner encabezado.
   3) Poner números de página automáticos.
   4) Mandar texto al documento, asignándole formato.
   5) Crear tablas de datos con cantidad de filas y columnas deseadas.
   6) Asignar formato a datos en las tablas de datos creadas.
   7) Imprimir una imagen en el documento.
   8) Imponer un ‘Break’, un brinco incondicional a la siguiente página.
   9) Enviar texto al documento e imponer alinación deseada: ‘left’, ‘center’, ‘right’ y ‘justify’.
   10) Enviar el documento a la impresora. (Nota: en este caso mi impresora fue ‘pdfCreator’).
   11) Guardar el documento, dado un nombre indicado y un folder señalado en el código.
   12) Cerrar el documento.




2. Recursos Software utilizados.
Se usó Visual C# 2008, y Microsoft Word 2007, con los resultados esperados y ya indicados. Nota: presumiblemente, no habría inconveniente que con
Visual C# 2010, y Microsoft Word 2010 se logren los mismos resultados.




                                                                                                                                   Página 6 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




3. Secuencia de Imágenes que prueban la creación y manipulación de un documento Word, desde código C#.




                                         Figura 1: Asignado formato al texto, y el encabezado de las páginas.



                                                                                                                Página 7 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                                     Figura 2: La primera tabla que se genera, y formatos asignados a sus datos.




                                                                                                                   Página 8 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                                                  Figura 3: Asignar números de página automáticos.




                                                                                                        Página 9 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                                 Figura 4: Asignando un ‘Break’, es decir, brinco incondicional a la siguiente página.




                                                                                                                         Página 10 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                                       Figura 5: Se generó una seguna tabla, con formato para algunos datos.




                                                                                                               Página 11 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                               Figura 6: Se generó un segundo ‘Break’, otro brinco incondicional a la página siguiente.




                                                                                                                          Página 12 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                               Figura 7: Se inserta una imagen en el documento, dentro de una tabla (esta, no visible).




                                                                                                                          Página 13 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                 Figura 8: Se envía 4 párrafos de texto al documento, con formato ‘right’, ‘left’, ‘center’ y ‘justify’, respectivamente.




                                                                                                                                            Página 14 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                        Figura 9: Orden de enviar el documento a la impresora. (En este caso, la impresora fue ‘PdfCreator’).



                                                                                                                                Página 15 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




                              Figura 10: Guardado automático del documento en el folder indicado desde el código C#.




                                                                                                                       Página 16 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




4. Primer paso: desde el IDE Visual C# agregar una referencia al proyecto, denominada Microsoft Word xx.x
Object Library

Para crear un documento Word desde un programa de C# el primer paso consiste en utilizar el botón derecho sobre el nombre del proyecto, y
seleccionar agregar referencia




                                                   Sobre nombre del Proyecto agregamos Referencia.



                                                                                                                                   Página 17 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.



Luego, elegimos la pestaña COM, y de esta, seleccionamos la biblioteca Microsoft Word xx.xx Object Library.




                                        De la pestaña COM, se selecciona Microsoft Word xx.x Object Library.




                                                                                                               Página 18 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




5. Elementos visuales que se insertan en la aplicación.




                                                   Elementos de arrastrar y pegar en la aplicación.



   a) Nombre del primer botón insertado (y único): Docto_Word.
   b) Nombre del segundo y último elemento utilizado: mensaje_de_word.


                                                                                                        Página 19 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.




6. Código C# para construir y manipular un documento Word.


// Inicia el código.

using   System;
using   System.Collections.Generic;
using   System.ComponentModel;
using   System.Data;
using   System.Drawing;
using   System.Linq;
using   System.Text;
using   System.Windows.Forms;
using   Microsoft.Office.Interop.Word;



namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

           private Microsoft.Office.Interop.Word.Application ApWord;
           private Microsoft.Office.Interop.Word.Document doc;
           private object opc = Type.Missing; // parámetro opcional

           public Form1()
           {
               InitializeComponent();
           }

           private void button1_Click(object sender, EventArgs e)
           {

                                                                                                        Página 20 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.


              ApWord = new Microsoft.Office.Interop.Word.Application();
              doc = ApWord.Documents.Add(ref opc, ref opc, ref opc, ref opc);
              doc.Range(ref opc, ref opc).Delete(ref opc, ref opc);

              //Visualizar un documento
              ApWord.Visible = true;


            // MessageBox.Show("Observar que el nuevo doc. Word no tiene contenido ...", "", MessageBoxButtons.OK,
MessageBoxIcon.Information);


              // ******************************************************************************

              // IMPORTANTE: La siguiente asignacion de tipo de letra y su tamaño, afecta a todo el documento Word.
              // con el mismo 'doc.Content.Font...' no se puede re-asignar nuevos valores,
              // porque re-afectaría incluso la configuración antes hecha.
              // Afecta todo el texto que siguira, hasta modificar otra vez estas indicaciones.
              doc.Content.Font.Name = "Calibri";
              doc.Content.Font.Size = 12;
              doc.Content.InsertAfter("1. Lines: 1, 2 y 3 en 'Calibri', tamaño = 12. n");

              // Insertar texto al final del texto del documento Word.
              doc.Range(ref opc, ref opc).InsertAfter("2. Now, the second text added.    n");
              doc.Range(ref opc, ref opc).InsertAfter("3. Now, the third text placed.    nn");

              // ******************************************************************************************************



              // **************************************************************************
              // ASIGNAR TIPO DE LETRA, Y TAMAÑO AL TEXTO FUNCIONA PERFECTAMENTE....

              object EndOfDoc1 = "endofdoc";
              Microsoft.Office.Interop.Word.Paragraph oPara1;
              object Rng1 = doc.Bookmarks.get_Item(ref EndOfDoc1).Range;
              Rng1 = doc.Bookmarks.get_Item(ref EndOfDoc1).Range;
              oPara1 = doc.Content.Paragraphs.Add(ref Rng1);
                                                                                                                Página 21 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.


              oPara1.Range.Font.Name = "Lucida Calligraphy";
              oPara1.Range.Font.Size = 18;
              oPara1.Range.Text = "Hecho por M.C. Enrique Ruiz Diaz ...(Lucida Calligraphy a 18)";
              oPara1.Range.InsertParagraphAfter(); // Se imprime ya en nuestro documento Word,
              // porque funciona como variable, su contenido es reemplazado a continuación.

              doc.Range(ref opc, ref opc).InsertAfter("n");

              oPara1.Range.Font.Name = "Courier New";
              oPara1.Range.Font.Size = 18;
              oPara1.Range.Text = "Maestro en Ciencias de la Computaciòn ...(Courier New a 18)";
              oPara1.Range.InsertParagraphAfter();

              doc.Range(ref opc, ref opc).InsertAfter("n");

              // OBSERVACION: Una asignación de tipo de letra y tamaño afecta, persiguiendo,
              // todo lo demás que siga a continuación. Excepto que se indique nuevas asignaciones.
              // **************************************************************************


              // ***************************************************************************************************
              // AÑADIR UNA TABLA DE DATOS ...
              //Insert a 5 x 2 table, fill it with data, and change the column widths.
              // parte de datos que debo antes tener, segun mis particulares pruebas

              object oMissing = System.Reflection.Missing.Value; //System.Reflection.Missing.Value;
              object oEndOfDoc = "endofdoc"; /* endofdoc is a predefined bookmark */

              Microsoft.Office.Interop.Word.Table oTable;
              Microsoft.Office.Interop.Word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;
              wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;
              oTable = doc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);
              oTable.Range.ParagraphFormat.SpaceAfter = 6;


              // asigno tamaño de letra que en general afectara a la siguiente tabla.
              // excepto cuando se indique otras asignaciones...

                                                                                                                Página 22 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

              oTable.Range.Font.Size = 12;



              int r, c;
              string strText;

              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 = ApWord.InchesToPoints(3); //Contrala ancho de la columna - confirmado
              oTable.Columns[2].Width = ApWord.InchesToPoints(2); ////Contrala ancho de la columna - confirmado

              // Sin bordes: oTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;
              // Sin bordes: oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;

              // Poner bordes a la tabla
              oTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
              oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;


              // Sobre la fila num. 1 ... a Negritas y cursiva sobre los datos ....
              oTable.Rows[1].Range.Font.Bold = 1;
              oTable.Rows[1].Range.Font.Italic = 1;

              oTable.Rows[2].Range.Font.Name = "Bradley Hand ITC";
              oTable.Rows[2].Range.Font.Size = 16;


              double   nPrecio = 258123658.39;
              double   nPrecio2 = -10201.78;
              double   nPrecio3 = -15987.89;
              double   nPrecio4 = 31325.49;


              oTable.Cell(4, 1).Range.Text = provide_format(nPrecio);
                                                                                                                  Página 23 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

            oTable.Cell(4, 1).Range.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

            oTable.Cell(3, 2).Range.Text = provide_format(nPrecio2);
            oTable.Cell(3, 2).Range.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

            oTable.Cell(4, 2).Range.Text = provide_format(nPrecio3); // la 'c' indica formato de Moneda
            oTable.Cell(4,2).Range.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

            oTable.Cell(5, 2).Range.Text = provide_format(nPrecio4);
            oTable.Cell(5, 2).Range.Font.Name = "Calibri";
            oTable.Cell(5, 2).Range.Font.Bold = 1;
            oTable.Cell(5, 2).Range.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;



              //   fin de añadir tabla de datos
              //   NOTA: de acabarse la hoja por el tamaño de la tabla. Word automaticamente
              //   añada una nueva hoja - COMPROBADO!
              //   ***************************************************************************************************

              // ........................................................................
              // Añadir otra cosa después de la Tabla.
              //Add some text after the table.




              // ***************************************************************************
              // FUNCIONÓ INSERTAR UN BREAK, NUEVA PÁGINA EN NUESTRO DOCUMENTO DE WORD
              // C# word automation : Inserting page break

              object o_EndOfDoc = "endofdoc";
              object paramNextPage = WdBreakType.wdSectionBreakNextPage;

              //wrdDocument.Bookmarks.get_Item(ref o_EndOfDoc).Range.InsertBreak(ref paramNextPage);
                                                                                                                  Página 24 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.


              doc.Bookmarks.get_Item(ref o_EndOfDoc).Range.InsertBreak(ref paramNextPage);


              oPara1.Range.Font.Name = "Britannic Bold";
              oPara1.Range.Font.Size = 14;

              oPara1.Range.Text = "Yo 'texto' debo salir en una nueva página, dado un 'BREAK' ... 'Britannic Bold' a 14
nn";
              oPara1.Range.InsertParagraphAfter();
              // ***************************************************************************


              oPara1.Range.Font.Size = 14;
              oPara1.Range.Font.Name = "Georgia";
              oPara1.Range.Text = "A continuaciòn una tabla de datos grande. Letra: 'Georgia' a 14 nn";
              oPara1.Range.InsertParagraphAfter();

              // ........................................................................
              // AÑADIDR UNA TABLA DE DATOS ...
              //Insert a 5 x 2 table, fill it with data, and change the column widths.
              // parte de datos que debo antes tener, segun mis particulares pruebas

              object oMissing2 = System.Reflection.Missing.Value;
              object oEndOfDoc2 = "endofdoc";

              Microsoft.Office.Interop.Word.Table oTable2;
              Microsoft.Office.Interop.Word.Range wrdRng2 = doc.Bookmarks.get_Item(ref oEndOfDoc2).Range;
              wrdRng2 = doc.Bookmarks.get_Item(ref oEndOfDoc2).Range;
              oTable2 = doc.Tables.Add(wrdRng2, 20, 2, ref oMissing, ref oMissing);
              oTable2.Range.ParagraphFormat.SpaceAfter = 6;

              //int r, c;      !YA EXPRESADAS ARRIBA
              //string strText; !YA EXPRESADAS ARRIBA

              for (r = 1; r <= 20; r++)
                  for (c = 1; c <= 2; c++)
                  {
                      strText = "row = " + r + "column = " + c;
                                                                                                                Página 25 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

                        oTable2.Cell(r, c).Range.Text = strText;
                   }

              oTable2.Columns[1].Width = ApWord.InchesToPoints(4);
              oTable2.Columns[2].Width = ApWord.InchesToPoints(2);

              // Sobre la fila num. 1 ... a Negritas y cursiva sobre los datos ....
              oTable2.Rows[1].Range.Font.Bold = 1;
              oTable2.Rows[1].Range.Font.Italic = 1;
              oTable2.Rows[1].Range.Font.Name = "Bradley Hand ITC";
              oTable2.Rows[1].Range.Font.Size = 18;

              // fin de añadir tabla de datos
              // NOTA: de acabarse la hoja por el tamaño de la tabla. Word automaticamente
              // añada una nueva hoja - COMPROBADO!

              // ........................................................................



              //************************************************************************
              // FIJANDO MARGENES TODO EL DOCUMENTO WORD.
              // COMPROBADO - Si el usuario normal de Word altera márgenes, no importa...
              // porque yo impongo mis márgenes para mi documento aquí creado ...


              object nothing = System.Reflection.Missing.Value;

            doc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperLetter;
            doc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;
            doc.PageSetup.TopMargin = 60.0f; // Distancia desde el encabezado hasta el primer texto para todas las hojas -
confirmado 57.0f;
            doc.PageSetup.BottomMargin = 60.0f; // Distancia del ultimo texto en cada hoja, hasta el pie de página -
confirmado ...
            doc.PageSetup.LeftMargin = 80.0f; // Afirmativo: este es para margen izquiedo para todas las hojas generadas...
            doc.PageSetup.RightMargin = 60.0f; // ... Posible- contrada distancia del margen derecho de cada hoja ...
            doc.PageSetup.HeaderDistance = 30.0f; // desconozco que controla, pero valor correcto debe ser 30.0f ...

              //************************************************************************
                                                                                                              Página 26 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.



              // ****************************************************************************************
              //How to insert <Current Page> of <Total Pages> into the footer for a MS Word Document in VSTO

              //Open up the footer in the word document
              doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;


            // Set current Paragraph Alignment to Center
            doc.ActiveWindow.ActivePane.Selection.Paragraphs.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

              // Type in 'Page '
              doc.ActiveWindow.Selection.TypeText("Page ");

              // Add in current page field
              Object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;

              doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref CurrentPage, ref opc, ref opc);

              // Type in ' of '
              doc.ActiveWindow.Selection.TypeText(" of ");

              // Add in total page field
              Object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages;
              doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref TotalPages, ref opc, ref opc);

            // Add header in the doc
            doc.Content.Application.ActiveWindow.ActivePane.View.SeekView =
Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;// =
Convert.ToInt32(Word.WdSeekView.wdSeekCurrentPageHeader);
            doc.Content.Application.Selection.TypeText("M.C. Enrique Ruiz Díaz.");

              doc.Content.Application.Selection.Fields.Add(doc.Content.Application.Selection.Range, ref opc, ref opc, ref
opc);
            //
****************************************************************************************************************
                                                                                                                Página 27 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.



              // ****************************************************************************************
              // AÑADIR UNA IMAGEN AL DOCUMENTO ...

              // Primero creo una tabla de una sola fila y una sola columna para allí poner la imagen.
              // Se trata ya, de la tercera tabla de mi docto.


              //******************************************************************************************
              // CONOCIMIENTO: NUNCA DEBES GENERAR DOS TABLAS EN FORMA CONSECUTIVA. DEBES SEPARARLO CON
              // TEXTO. COMO SIGUE A CONTINUACIÒN. SE GENERA ERROR DE NO HACERSE ASI.
              // TABLA SIGUIENTE 1X1, SOLO PARA LA IMAGEN A AGREGARSE.

            oPara1.Range.Font.Size = 14;
            oPara1.Range.Font.Name = "Calibri";
            oPara1.Range.Text = "n n n Sigue una tercera tabla con una sola fila y una sola columna. Para IMAGEN ...
Letra: 'Calibri' a 14 nn";
            oPara1.Range.InsertParagraphAfter();


              // Creamos una nueva tabla de 1 x 1 solo para insertar una imagen ....
              object oMissing3 = System.Reflection.Missing.Value;
              object oEndOfDoc3 = "endofdoc";

              Microsoft.Office.Interop.Word.Table oTable3;
              Microsoft.Office.Interop.Word.Range wrdRng3 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range;
              wrdRng3 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range;
              oTable3 = doc.Tables.Add(wrdRng3, 1, 1, ref oMissing3, ref oMissing3);
              oTable3.Range.ParagraphFormat.SpaceAfter = 6;

              //oTable3.Cell(1, 1).Range.Text = "una fila, una columna";
              oTable3.Columns[1].Width = ApWord.InchesToPoints(3);


              // ***********************************************************************************

              object missing = System.Reflection.Missing.Value;
                                                                                                              Página 28 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

              object start1 = 0;

              Range rng = doc.Range(ref start1, ref missing);

              Range rngPic = doc.Tables[3].Range;

              rngPic.InlineShapes.AddPicture(@"C:ImagenThe Vision.jpg", ref missing, ref missing, ref missing);


              // *********************************************************************************************


              // ***************************************************************************
              // RECURRO A UN SEGUDO 'BREAK'. SIGNIFICA UN NUEVO BRINCO DE PAGINA.
              // C# word automation : Inserting page break

              object o_EndOfDoc5 = "endofdoc";
              object paramNextPage5 = WdBreakType.wdSectionBreakNextPage;

              //wrdDocument.Bookmarks.get_Item(ref o_EndOfDoc5).Range.InsertBreak(ref paramNextPage5);

              doc.Bookmarks.get_Item(ref o_EndOfDoc).Range.InsertBreak(ref paramNextPage);


              oPara1.Range.Font.Name = "Footlight MT Light";
              oPara1.Range.Font.Size = 14;

            oPara1.Range.Text = "Este es un nuevo BREAK (el segundo). Debo salir en una nueva página, dado un 'BREAK' ...
'Footlight MT Light' a 14 nn";
            oPara1.Range.InsertParagraphAfter();


              // ***************************************************************************

              // ALINEACION AL CENTRO, A LA IZQUIERA JUSTIFICADO Y A LA DERECHA

              string var5 = "[right] «You attitude determines your altitude».";
              string var6 = "[left] «As a diamond, the English Language is forever».";
              string var7 = "[center] «Siempre hay un lugar en la cima».";
                                                                                                                 Página 29 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.


              string   var8a   =   "[justify] «Avoid sugar, salt, white flour products or deserts. ";
              string   var8b   =   "Avoid soft drinks and candy bars or pastries. ";
              string   var8c   =   "Feed yourself as you would feed a world class athlete before a competition, ";
              string   var8d   =   "because in many respects, ";
              string   var8e   =   "that is what you are before starting work each day».";


              Microsoft.Office.Interop.Word.Table oTable5;
              Microsoft.Office.Interop.Word.Range wrdRng5 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range;
              wrdRng5 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range;
              oTable5 = doc.Tables.Add(wrdRng5, 4, 1, ref oMissing3, ref oMissing3);
              oTable5.Range.ParagraphFormat.SpaceAfter = 6;


            oTable5.Cell(1, 1).Range.Text = var5;
            oTable5.Cell(1, 1).Range.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

            oTable5.Cell(2, 1).Range.Text = var6;
            oTable5.Cell(2, 1).Range.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

            oTable5.Cell(3, 1).Range.Text = var7;
            oTable5.Cell(3, 1).Range.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

            oTable5.Cell(4, 1).Range.Text = var8a + var8b + var8c + var8d + var8e;
            oTable5.Cell(4, 1).Range.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;

              // ******************************************************************************

            //Enviar a la impresora
            ApWord.ActiveDocument.PrintOut(ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc,
ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc);

              String nuevoNombreDoc = @"C:ImagenPoliza_01.docx";

                                                                                                                     Página 30 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

              object param = nuevoNombreDoc;


            MessageBox.Show("Requiere IMPRIMIR, primero. Luego pulse aquí ...", "", MessageBoxButtons.OK,
MessageBoxIcon.Information);



              try
              {

                    //Para guardar los cambios y además, asignar un nombre a nuestro docto. Word.

                doc.SaveAs(ref param, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref
opc, ref opc, ref opc, ref opc, ref opc, ref opc);

                    //Cuando la ventana Word está visible y se cierra.
                    ApWord.Visible = false;
                    ApWord.Quit(ref opc, ref opc, ref opc);
                    ApWord = null;
                    doc = null;
                    mensaje_de_word.Text = "Word se acaba de cerrar, para mi propio docto. No para otro ajeno ...";
            }
            catch
            {
                MessageBox.Show("Word no requiere cerrarse, ya está cerrado...", "", MessageBoxButtons.OK,
MessageBoxIcon.Error);

              }

         }


         private string provide_format(double num)
             {


                    string var_String = string.Format("Order Total: {0:C}", num); //string.Format("{0:#,###.00}", num);
                    string resultado = "";
                                                                                                                  Página 31 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.


                for (int i=0; i<var_String.Length; i++) //(int i = var_String.Length-1; i>=0; i--)
                        {
                             if (var_String[i] == '-' || var_String[i] == '0' || var_String[i] == '1' || var_String[i] ==
'2' || var_String[i] == '3' || var_String[i] == '4' || var_String[i] == '5' || var_String[i] == '6' || var_String[i] == '7'
|| var_String[i] == '8' || var_String[i] == '9')
                                 {
                                     resultado = resultado + var_String[i];
                                 }
                        else
                                 {
                                     if (var_String[i] == '.')
                                          {
                                          resultado = resultado + ',';
                                          }
                                     else
                                          {
                                              if (var_String[i] == ',')
                                                  {
                                                  resultado = resultado + '.';
                                                  }
                                          } // fin del segundo else
                                 } // fin del primer else

                             } // fin del for


                     return resultado;
               }



    } // de la clase
} // del NameSpace

// Fin del código.


                                                                                                              Página 32 de 32
Visit: https://sites.google.com/site/mcenriqueruizdiaz/
Also: http://sites.google.com/site/enriqueruizdiaz/

Más contenido relacionado

Destacado (20)

NARREMOS CUENTOS
NARREMOS CUENTOSNARREMOS CUENTOS
NARREMOS CUENTOS
 
Sesion 12-c#
Sesion 12-c#Sesion 12-c#
Sesion 12-c#
 
Sesion 10-c#
Sesion 10-c#Sesion 10-c#
Sesion 10-c#
 
Hotel resort el olimpo
Hotel resort el olimpoHotel resort el olimpo
Hotel resort el olimpo
 
Anteproyecto Turistico Desembocadura del Río Grande de Matagalpa
Anteproyecto Turistico Desembocadura del Río Grande de MatagalpaAnteproyecto Turistico Desembocadura del Río Grande de Matagalpa
Anteproyecto Turistico Desembocadura del Río Grande de Matagalpa
 
Prueba enlace 2011 preparación 3° grado
Prueba enlace 2011 preparación 3° gradoPrueba enlace 2011 preparación 3° grado
Prueba enlace 2011 preparación 3° grado
 
C# DidáCtico
C# DidáCticoC# DidáCtico
C# DidáCtico
 
HOTEL RESORT "EL OLIMPO"
HOTEL RESORT "EL OLIMPO"HOTEL RESORT "EL OLIMPO"
HOTEL RESORT "EL OLIMPO"
 
Programacion iv sesion11 php
Programacion iv sesion11 phpProgramacion iv sesion11 php
Programacion iv sesion11 php
 
Anteproyecto turistico monos resort
Anteproyecto turistico monos resortAnteproyecto turistico monos resort
Anteproyecto turistico monos resort
 
SUMAS LLEVANDO
SUMAS LLEVANDOSUMAS LLEVANDO
SUMAS LLEVANDO
 
Tutorial c# y Video Juegos
Tutorial c# y Video JuegosTutorial c# y Video Juegos
Tutorial c# y Video Juegos
 
PresentacióN Joint Venture.Ppt1111
PresentacióN Joint Venture.Ppt1111PresentacióN Joint Venture.Ppt1111
PresentacióN Joint Venture.Ppt1111
 
Practicas sencillas para C#
Practicas sencillas para C# Practicas sencillas para C#
Practicas sencillas para C#
 
Yajani
Yajani Yajani
Yajani
 
01 autofinanciamiento
01 autofinanciamiento01 autofinanciamiento
01 autofinanciamiento
 
Clases de propiedad
Clases de propiedadClases de propiedad
Clases de propiedad
 
Todo sobre C#
Todo sobre C#Todo sobre C#
Todo sobre C#
 
Atributos o Facultades del Dominio 02 - Derecho Civil I
Atributos o Facultades del Dominio 02 - Derecho Civil IAtributos o Facultades del Dominio 02 - Derecho Civil I
Atributos o Facultades del Dominio 02 - Derecho Civil I
 
Copropiedad, condominio y tiempo compartido
Copropiedad, condominio y tiempo compartidoCopropiedad, condominio y tiempo compartido
Copropiedad, condominio y tiempo compartido
 

Similar a C# and create and handle a word document, by m.c. enrique ruiz díaz

tutorial de informatica
tutorial  de informaticatutorial  de informatica
tutorial de informaticakarolinaP2001
 
Presentación sobre el diseño en 3D
Presentación sobre el diseño en 3D Presentación sobre el diseño en 3D
Presentación sobre el diseño en 3D HillarySnchez1
 
Unidad educativa javeriano
Unidad educativa javerianoUnidad educativa javeriano
Unidad educativa javerianodiana25182
 
tutorial de informatica
tutorial de informaticatutorial de informatica
tutorial de informaticadiana5634
 
tutorial de informatica
tutorial  de informatica tutorial  de informatica
tutorial de informatica Japositib
 
Japon bryam 0987t6t6
Japon bryam 0987t6t6Japon bryam 0987t6t6
Japon bryam 0987t6t6Japositib
 
MediaLab MIT y sus aportes al pensamiento computacional desde la edad escolar
MediaLab MIT y sus aportes al pensamiento computacional desde la edad escolarMediaLab MIT y sus aportes al pensamiento computacional desde la edad escolar
MediaLab MIT y sus aportes al pensamiento computacional desde la edad escolarOriana Robles Muñoz
 
Portfolio 2012-2013 Acciones Formativas LR SOUL
Portfolio 2012-2013 Acciones Formativas LR SOULPortfolio 2012-2013 Acciones Formativas LR SOUL
Portfolio 2012-2013 Acciones Formativas LR SOULLaura Rosillo Cascante
 
Herramientas de comunicación para el trabajo colaborativo
Herramientas de comunicación para el trabajo colaborativoHerramientas de comunicación para el trabajo colaborativo
Herramientas de comunicación para el trabajo colaborativosebasperez9597
 
--- tutorial de informatica ----
--- tutorial de informatica  ------- tutorial de informatica  ----
--- tutorial de informatica ----nellyye654
 
tutorial de informatica
tutorial de informaticatutorial de informatica
tutorial de informaticavaleria1711
 
tutorial de informatica
tutorial de informaticatutorial de informatica
tutorial de informaticavaleria1711
 
EducacióN TecnolóGica 2007
EducacióN TecnolóGica 2007EducacióN TecnolóGica 2007
EducacióN TecnolóGica 2007Bruna Concha
 
Design thinking slides
Design thinking  slidesDesign thinking  slides
Design thinking slidesMoises Cielak
 
tutorial de informatica
tutorial  de informaticatutorial  de informatica
tutorial de informatica11steven11
 

Similar a C# and create and handle a word document, by m.c. enrique ruiz díaz (20)

tutorial de informatica
tutorial  de informaticatutorial  de informatica
tutorial de informatica
 
Presentación sobre el diseño en 3D
Presentación sobre el diseño en 3D Presentación sobre el diseño en 3D
Presentación sobre el diseño en 3D
 
Unidad educativa javeriano
Unidad educativa javerianoUnidad educativa javeriano
Unidad educativa javeriano
 
tutorial de informatica
tutorial de informaticatutorial de informatica
tutorial de informatica
 
tutorial de informatica
tutorial  de informatica tutorial  de informatica
tutorial de informatica
 
CREACION CONTENIDOS Mie (7 a 10 am).pptx
CREACION CONTENIDOS Mie (7 a 10 am).pptxCREACION CONTENIDOS Mie (7 a 10 am).pptx
CREACION CONTENIDOS Mie (7 a 10 am).pptx
 
Japon bryam 0987t6t6
Japon bryam 0987t6t6Japon bryam 0987t6t6
Japon bryam 0987t6t6
 
MediaLab MIT y sus aportes al pensamiento computacional desde la edad escolar
MediaLab MIT y sus aportes al pensamiento computacional desde la edad escolarMediaLab MIT y sus aportes al pensamiento computacional desde la edad escolar
MediaLab MIT y sus aportes al pensamiento computacional desde la edad escolar
 
MODULO TECNOLOGIA 8.pdf
MODULO TECNOLOGIA 8.pdfMODULO TECNOLOGIA 8.pdf
MODULO TECNOLOGIA 8.pdf
 
Portfolio 2012-2013 Acciones Formativas LR SOUL
Portfolio 2012-2013 Acciones Formativas LR SOULPortfolio 2012-2013 Acciones Formativas LR SOUL
Portfolio 2012-2013 Acciones Formativas LR SOUL
 
Herramientas de comunicación para el trabajo colaborativo
Herramientas de comunicación para el trabajo colaborativoHerramientas de comunicación para el trabajo colaborativo
Herramientas de comunicación para el trabajo colaborativo
 
--- tutorial de informatica ----
--- tutorial de informatica  ------- tutorial de informatica  ----
--- tutorial de informatica ----
 
Etapas del proyecto
Etapas del proyectoEtapas del proyecto
Etapas del proyecto
 
tutorial de informatica
tutorial de informaticatutorial de informatica
tutorial de informatica
 
tutorial de informatica
tutorial de informaticatutorial de informatica
tutorial de informatica
 
EducacióN TecnolóGica 2007
EducacióN TecnolóGica 2007EducacióN TecnolóGica 2007
EducacióN TecnolóGica 2007
 
Técnicas para generar ideas
Técnicas para generar ideasTécnicas para generar ideas
Técnicas para generar ideas
 
SECUENCIA DIDACTICA
SECUENCIA DIDACTICASECUENCIA DIDACTICA
SECUENCIA DIDACTICA
 
Design thinking slides
Design thinking  slidesDesign thinking  slides
Design thinking slides
 
tutorial de informatica
tutorial  de informaticatutorial  de informatica
tutorial de informatica
 

Más de enriqueruizdiaz

1240 quotes m.c. enrique ruiz diaz
1240 quotes   m.c. enrique ruiz diaz1240 quotes   m.c. enrique ruiz diaz
1240 quotes m.c. enrique ruiz diazenriqueruizdiaz
 
Leadership 100and5 stars - theme 15 -
Leadership   100and5 stars - theme 15 -Leadership   100and5 stars - theme 15 -
Leadership 100and5 stars - theme 15 -enriqueruizdiaz
 
Third book of english readings m.c. enrique ruiz díaz, for you
Third book of english readings   m.c. enrique ruiz díaz, for youThird book of english readings   m.c. enrique ruiz díaz, for you
Third book of english readings m.c. enrique ruiz díaz, for youenriqueruizdiaz
 
The second book of english readings of m.c. enrique ruiz díaz
The second book of english readings of m.c. enrique ruiz díazThe second book of english readings of m.c. enrique ruiz díaz
The second book of english readings of m.c. enrique ruiz díazenriqueruizdiaz
 
Neuronas espejo, y el poder de leer m.c. enrique ruiz díaz
Neuronas espejo, y el poder de leer   m.c. enrique ruiz díazNeuronas espejo, y el poder de leer   m.c. enrique ruiz díaz
Neuronas espejo, y el poder de leer m.c. enrique ruiz díazenriqueruizdiaz
 
La fotografía del éxito m.c. enrique ruiz díaz
La fotografía del éxito   m.c. enrique ruiz díazLa fotografía del éxito   m.c. enrique ruiz díaz
La fotografía del éxito m.c. enrique ruiz díazenriqueruizdiaz
 
The importance of the english language ...
The importance of the english language ...The importance of the english language ...
The importance of the english language ...enriqueruizdiaz
 
The first book of english readings of m.c. enrique ruiz díaz
The first book of english readings of m.c. enrique ruiz díazThe first book of english readings of m.c. enrique ruiz díaz
The first book of english readings of m.c. enrique ruiz díazenriqueruizdiaz
 
Aprendamos del gran maestro jw-org
Aprendamos del gran maestro   jw-orgAprendamos del gran maestro   jw-org
Aprendamos del gran maestro jw-orgenriqueruizdiaz
 
Mexico y el primer mundo
Mexico y el primer mundoMexico y el primer mundo
Mexico y el primer mundoenriqueruizdiaz
 
La concentración, el adn del liderazgo
La concentración, el adn del liderazgoLa concentración, el adn del liderazgo
La concentración, el adn del liderazgoenriqueruizdiaz
 
El pensamiento crítico visto por m.c. enrique ruiz díaz
El pensamiento crítico visto por m.c. enrique ruiz díazEl pensamiento crítico visto por m.c. enrique ruiz díaz
El pensamiento crítico visto por m.c. enrique ruiz díazenriqueruizdiaz
 
The phrasal verbs, by m.c. enrique ruiz díaz
The phrasal verbs, by m.c. enrique ruiz díazThe phrasal verbs, by m.c. enrique ruiz díaz
The phrasal verbs, by m.c. enrique ruiz díazenriqueruizdiaz
 
Lo que 'leader summaries logros extraordinarios' ignora
Lo que 'leader summaries   logros extraordinarios' ignoraLo que 'leader summaries   logros extraordinarios' ignora
Lo que 'leader summaries logros extraordinarios' ignoraenriqueruizdiaz
 
Por qué es importante para usted el leer 20 minutos al día
Por qué es importante para usted el leer 20 minutos al díaPor qué es importante para usted el leer 20 minutos al día
Por qué es importante para usted el leer 20 minutos al díaenriqueruizdiaz
 
Bases de datos ii m.c. enrique ruiz díaz
Bases de datos ii   m.c. enrique ruiz díazBases de datos ii   m.c. enrique ruiz díaz
Bases de datos ii m.c. enrique ruiz díazenriqueruizdiaz
 
Bases de datos i m.c. enrique ruiz díaz
Bases de datos i   m.c. enrique ruiz díazBases de datos i   m.c. enrique ruiz díaz
Bases de datos i m.c. enrique ruiz díazenriqueruizdiaz
 
Regular and irregular verbs, by m.c. enrique ruiz díaz
Regular and irregular verbs, by m.c. enrique ruiz díazRegular and irregular verbs, by m.c. enrique ruiz díaz
Regular and irregular verbs, by m.c. enrique ruiz díazenriqueruizdiaz
 

Más de enriqueruizdiaz (20)

1240 quotes m.c. enrique ruiz diaz
1240 quotes   m.c. enrique ruiz diaz1240 quotes   m.c. enrique ruiz diaz
1240 quotes m.c. enrique ruiz diaz
 
Leadership 100and5 stars - theme 15 -
Leadership   100and5 stars - theme 15 -Leadership   100and5 stars - theme 15 -
Leadership 100and5 stars - theme 15 -
 
Third book of english readings m.c. enrique ruiz díaz, for you
Third book of english readings   m.c. enrique ruiz díaz, for youThird book of english readings   m.c. enrique ruiz díaz, for you
Third book of english readings m.c. enrique ruiz díaz, for you
 
The second book of english readings of m.c. enrique ruiz díaz
The second book of english readings of m.c. enrique ruiz díazThe second book of english readings of m.c. enrique ruiz díaz
The second book of english readings of m.c. enrique ruiz díaz
 
Neuronas espejo, y el poder de leer m.c. enrique ruiz díaz
Neuronas espejo, y el poder de leer   m.c. enrique ruiz díazNeuronas espejo, y el poder de leer   m.c. enrique ruiz díaz
Neuronas espejo, y el poder de leer m.c. enrique ruiz díaz
 
La fotografía del éxito m.c. enrique ruiz díaz
La fotografía del éxito   m.c. enrique ruiz díazLa fotografía del éxito   m.c. enrique ruiz díaz
La fotografía del éxito m.c. enrique ruiz díaz
 
The importance of the english language ...
The importance of the english language ...The importance of the english language ...
The importance of the english language ...
 
The first book of english readings of m.c. enrique ruiz díaz
The first book of english readings of m.c. enrique ruiz díazThe first book of english readings of m.c. enrique ruiz díaz
The first book of english readings of m.c. enrique ruiz díaz
 
Aprendamos del gran maestro jw-org
Aprendamos del gran maestro   jw-orgAprendamos del gran maestro   jw-org
Aprendamos del gran maestro jw-org
 
Nhsm
NhsmNhsm
Nhsm
 
Mexico y el primer mundo
Mexico y el primer mundoMexico y el primer mundo
Mexico y el primer mundo
 
La concentración, el adn del liderazgo
La concentración, el adn del liderazgoLa concentración, el adn del liderazgo
La concentración, el adn del liderazgo
 
The mayan civilization
The mayan civilizationThe mayan civilization
The mayan civilization
 
El pensamiento crítico visto por m.c. enrique ruiz díaz
El pensamiento crítico visto por m.c. enrique ruiz díazEl pensamiento crítico visto por m.c. enrique ruiz díaz
El pensamiento crítico visto por m.c. enrique ruiz díaz
 
The phrasal verbs, by m.c. enrique ruiz díaz
The phrasal verbs, by m.c. enrique ruiz díazThe phrasal verbs, by m.c. enrique ruiz díaz
The phrasal verbs, by m.c. enrique ruiz díaz
 
Lo que 'leader summaries logros extraordinarios' ignora
Lo que 'leader summaries   logros extraordinarios' ignoraLo que 'leader summaries   logros extraordinarios' ignora
Lo que 'leader summaries logros extraordinarios' ignora
 
Por qué es importante para usted el leer 20 minutos al día
Por qué es importante para usted el leer 20 minutos al díaPor qué es importante para usted el leer 20 minutos al día
Por qué es importante para usted el leer 20 minutos al día
 
Bases de datos ii m.c. enrique ruiz díaz
Bases de datos ii   m.c. enrique ruiz díazBases de datos ii   m.c. enrique ruiz díaz
Bases de datos ii m.c. enrique ruiz díaz
 
Bases de datos i m.c. enrique ruiz díaz
Bases de datos i   m.c. enrique ruiz díazBases de datos i   m.c. enrique ruiz díaz
Bases de datos i m.c. enrique ruiz díaz
 
Regular and irregular verbs, by m.c. enrique ruiz díaz
Regular and irregular verbs, by m.c. enrique ruiz díazRegular and irregular verbs, by m.c. enrique ruiz díaz
Regular and irregular verbs, by m.c. enrique ruiz díaz
 

Último

ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...JAVIER SOLIS NOYOLA
 
Registro Auxiliar - Primaria 2024 (1).pptx
Registro Auxiliar - Primaria  2024 (1).pptxRegistro Auxiliar - Primaria  2024 (1).pptx
Registro Auxiliar - Primaria 2024 (1).pptxFelicitasAsuncionDia
 
Identificación de componentes Hardware del PC
Identificación de componentes Hardware del PCIdentificación de componentes Hardware del PC
Identificación de componentes Hardware del PCCesarFernandez937857
 
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdfCurso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdfFrancisco158360
 
TIPOLOGÍA TEXTUAL- EXPOSICIÓN Y ARGUMENTACIÓN.pptx
TIPOLOGÍA TEXTUAL- EXPOSICIÓN Y ARGUMENTACIÓN.pptxTIPOLOGÍA TEXTUAL- EXPOSICIÓN Y ARGUMENTACIÓN.pptx
TIPOLOGÍA TEXTUAL- EXPOSICIÓN Y ARGUMENTACIÓN.pptxlclcarmen
 
Informatica Generalidades - Conceptos Básicos
Informatica Generalidades - Conceptos BásicosInformatica Generalidades - Conceptos Básicos
Informatica Generalidades - Conceptos BásicosCesarFernandez937857
 
la unidad de s sesion edussssssssssssssscacio fisca
la unidad de s sesion edussssssssssssssscacio fiscala unidad de s sesion edussssssssssssssscacio fisca
la unidad de s sesion edussssssssssssssscacio fiscaeliseo91
 
EXPANSIÓN ECONÓMICA DE OCCIDENTE LEÓN.pptx
EXPANSIÓN ECONÓMICA DE OCCIDENTE LEÓN.pptxEXPANSIÓN ECONÓMICA DE OCCIDENTE LEÓN.pptx
EXPANSIÓN ECONÓMICA DE OCCIDENTE LEÓN.pptxPryhaSalam
 
ACUERDO MINISTERIAL 078-ORGANISMOS ESCOLARES..pptx
ACUERDO MINISTERIAL 078-ORGANISMOS ESCOLARES..pptxACUERDO MINISTERIAL 078-ORGANISMOS ESCOLARES..pptx
ACUERDO MINISTERIAL 078-ORGANISMOS ESCOLARES..pptxzulyvero07
 
RETO MES DE ABRIL .............................docx
RETO MES DE ABRIL .............................docxRETO MES DE ABRIL .............................docx
RETO MES DE ABRIL .............................docxAna Fernandez
 
MAYO 1 PROYECTO día de la madre el amor más grande
MAYO 1 PROYECTO día de la madre el amor más grandeMAYO 1 PROYECTO día de la madre el amor más grande
MAYO 1 PROYECTO día de la madre el amor más grandeMarjorie Burga
 
30-de-abril-plebiscito-1902_240420_104511.pdf
30-de-abril-plebiscito-1902_240420_104511.pdf30-de-abril-plebiscito-1902_240420_104511.pdf
30-de-abril-plebiscito-1902_240420_104511.pdfgimenanahuel
 
Sesión de aprendizaje Planifica Textos argumentativo.docx
Sesión de aprendizaje Planifica Textos argumentativo.docxSesión de aprendizaje Planifica Textos argumentativo.docx
Sesión de aprendizaje Planifica Textos argumentativo.docxMaritzaRetamozoVera
 
Dinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes dDinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes dstEphaniiie
 
Qué es la Inteligencia artificial generativa
Qué es la Inteligencia artificial generativaQué es la Inteligencia artificial generativa
Qué es la Inteligencia artificial generativaDecaunlz
 
el CTE 6 DOCENTES 2 2023-2024abcdefghijoklmnñopqrstuvwxyz
el CTE 6 DOCENTES 2 2023-2024abcdefghijoklmnñopqrstuvwxyzel CTE 6 DOCENTES 2 2023-2024abcdefghijoklmnñopqrstuvwxyz
el CTE 6 DOCENTES 2 2023-2024abcdefghijoklmnñopqrstuvwxyzprofefilete
 
2024 - Expo Visibles - Visibilidad Lesbica.pdf
2024 - Expo Visibles - Visibilidad Lesbica.pdf2024 - Expo Visibles - Visibilidad Lesbica.pdf
2024 - Expo Visibles - Visibilidad Lesbica.pdfBaker Publishing Company
 

Último (20)

ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
ACERTIJO DE LA BANDERA OLÍMPICA CON ECUACIONES DE LA CIRCUNFERENCIA. Por JAVI...
 
Registro Auxiliar - Primaria 2024 (1).pptx
Registro Auxiliar - Primaria  2024 (1).pptxRegistro Auxiliar - Primaria  2024 (1).pptx
Registro Auxiliar - Primaria 2024 (1).pptx
 
Power Point: "Defendamos la verdad".pptx
Power Point: "Defendamos la verdad".pptxPower Point: "Defendamos la verdad".pptx
Power Point: "Defendamos la verdad".pptx
 
Identificación de componentes Hardware del PC
Identificación de componentes Hardware del PCIdentificación de componentes Hardware del PC
Identificación de componentes Hardware del PC
 
Medición del Movimiento Online 2024.pptx
Medición del Movimiento Online 2024.pptxMedición del Movimiento Online 2024.pptx
Medición del Movimiento Online 2024.pptx
 
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdfCurso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
 
TIPOLOGÍA TEXTUAL- EXPOSICIÓN Y ARGUMENTACIÓN.pptx
TIPOLOGÍA TEXTUAL- EXPOSICIÓN Y ARGUMENTACIÓN.pptxTIPOLOGÍA TEXTUAL- EXPOSICIÓN Y ARGUMENTACIÓN.pptx
TIPOLOGÍA TEXTUAL- EXPOSICIÓN Y ARGUMENTACIÓN.pptx
 
Informatica Generalidades - Conceptos Básicos
Informatica Generalidades - Conceptos BásicosInformatica Generalidades - Conceptos Básicos
Informatica Generalidades - Conceptos Básicos
 
la unidad de s sesion edussssssssssssssscacio fisca
la unidad de s sesion edussssssssssssssscacio fiscala unidad de s sesion edussssssssssssssscacio fisca
la unidad de s sesion edussssssssssssssscacio fisca
 
EXPANSIÓN ECONÓMICA DE OCCIDENTE LEÓN.pptx
EXPANSIÓN ECONÓMICA DE OCCIDENTE LEÓN.pptxEXPANSIÓN ECONÓMICA DE OCCIDENTE LEÓN.pptx
EXPANSIÓN ECONÓMICA DE OCCIDENTE LEÓN.pptx
 
ACUERDO MINISTERIAL 078-ORGANISMOS ESCOLARES..pptx
ACUERDO MINISTERIAL 078-ORGANISMOS ESCOLARES..pptxACUERDO MINISTERIAL 078-ORGANISMOS ESCOLARES..pptx
ACUERDO MINISTERIAL 078-ORGANISMOS ESCOLARES..pptx
 
Power Point: Fe contra todo pronóstico.pptx
Power Point: Fe contra todo pronóstico.pptxPower Point: Fe contra todo pronóstico.pptx
Power Point: Fe contra todo pronóstico.pptx
 
RETO MES DE ABRIL .............................docx
RETO MES DE ABRIL .............................docxRETO MES DE ABRIL .............................docx
RETO MES DE ABRIL .............................docx
 
MAYO 1 PROYECTO día de la madre el amor más grande
MAYO 1 PROYECTO día de la madre el amor más grandeMAYO 1 PROYECTO día de la madre el amor más grande
MAYO 1 PROYECTO día de la madre el amor más grande
 
30-de-abril-plebiscito-1902_240420_104511.pdf
30-de-abril-plebiscito-1902_240420_104511.pdf30-de-abril-plebiscito-1902_240420_104511.pdf
30-de-abril-plebiscito-1902_240420_104511.pdf
 
Sesión de aprendizaje Planifica Textos argumentativo.docx
Sesión de aprendizaje Planifica Textos argumentativo.docxSesión de aprendizaje Planifica Textos argumentativo.docx
Sesión de aprendizaje Planifica Textos argumentativo.docx
 
Dinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes dDinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes d
 
Qué es la Inteligencia artificial generativa
Qué es la Inteligencia artificial generativaQué es la Inteligencia artificial generativa
Qué es la Inteligencia artificial generativa
 
el CTE 6 DOCENTES 2 2023-2024abcdefghijoklmnñopqrstuvwxyz
el CTE 6 DOCENTES 2 2023-2024abcdefghijoklmnñopqrstuvwxyzel CTE 6 DOCENTES 2 2023-2024abcdefghijoklmnñopqrstuvwxyz
el CTE 6 DOCENTES 2 2023-2024abcdefghijoklmnñopqrstuvwxyz
 
2024 - Expo Visibles - Visibilidad Lesbica.pdf
2024 - Expo Visibles - Visibilidad Lesbica.pdf2024 - Expo Visibles - Visibilidad Lesbica.pdf
2024 - Expo Visibles - Visibilidad Lesbica.pdf
 

C# and create and handle a word document, by m.c. enrique ruiz díaz

  • 1. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. All Rigths Reserved. Con título y cédula profesional 5632071 en la Maestría en Ciencias de la Computación. Egresado del Instituto Tecnológico de Orizaba, Ver. (México). Página 1 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 2. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Acerca de mi. Titulado en la Maestría en Ciencias en Ciencias de la Computación, Cédula profesional 5632071. Egresado del Instituto Tecnológico de Orizaba, Ver., México. Antes, me Titulé en la Licenciatura en Informática, Cédula profesional 4046033. Egresado del Instituto Tecnológico de Tuxtepec, Oax., México, distinguiéndome además, por ser el mejor promedio de mi generación con 98%. Bien, regresando al tema de mi Título de Maestría en Ciencias de la Computación, para subrayar que ésta, requirió el desarrollo de una TESIS. Otro aspecto muy importante, fue que durante el desarrollo de mi Maestría escribí un ARTICULO, mismo que fue aceptado para publicación y con mi ponencia en el evento 'Primer Encuentro de Estudiantes en Ciencia de la Computación - E2C2' ISBN-10:970-36-0404-8 e ISBN-13:978-970-36-0404-3 celebrado en el Instituto Politécnico Nacional, México, D.F. 2007. Página 2 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 3. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Mi Diploma por mi Ponencia en el Instituto Politécnico Nacional, México, D.F. 2007. Página 3 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 4. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. «Inside the great field of the Programming, I own to offer my knowledge of the Structured Programming Paradigm. This, principally by means of the Language C. Also, I own to offer my knowledge of the Object-Oriented Paradigm. This, by means of The Languages Java and Visual C#. Majorly». M.C. Enrique Ruiz Díaz. Página 4 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 5. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. ÍNDICE Acerca de mi. ............................................................................................................................................................. 2 ÍNDICE ........................................................................................................................................................................ 5 1. Lista de objetivos que logra el código C# presentado para la manipulación de un documento Word. .................. 6 2. Recursos Software utilizados. ................................................................................................................................ 6 3. Secuencia de Imágenes que prueban la creación y manipulación de un documento Word, desde código C#. ..... 7 4. Primer paso: desde el IDE Visual C# agregar una referencia al proyecto, denominada Microsoft Word xx.x Object Library .......................................................................................................................................................... 17 5. Elementos visuales que se insertan en la aplicación. ........................................................................................... 19 6. Código C# para construir y manipular un documento Word. ............................................................................... 20 Página 5 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 6. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. 1. Lista de objetivos que logra el código C# presentado para la manipulación de un documento Word. 1) Asignar márgenes a la hoja, para nuestro documento, independientes de márgenes en Word indicados. 2) Poner encabezado. 3) Poner números de página automáticos. 4) Mandar texto al documento, asignándole formato. 5) Crear tablas de datos con cantidad de filas y columnas deseadas. 6) Asignar formato a datos en las tablas de datos creadas. 7) Imprimir una imagen en el documento. 8) Imponer un ‘Break’, un brinco incondicional a la siguiente página. 9) Enviar texto al documento e imponer alinación deseada: ‘left’, ‘center’, ‘right’ y ‘justify’. 10) Enviar el documento a la impresora. (Nota: en este caso mi impresora fue ‘pdfCreator’). 11) Guardar el documento, dado un nombre indicado y un folder señalado en el código. 12) Cerrar el documento. 2. Recursos Software utilizados. Se usó Visual C# 2008, y Microsoft Word 2007, con los resultados esperados y ya indicados. Nota: presumiblemente, no habría inconveniente que con Visual C# 2010, y Microsoft Word 2010 se logren los mismos resultados. Página 6 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 7. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. 3. Secuencia de Imágenes que prueban la creación y manipulación de un documento Word, desde código C#. Figura 1: Asignado formato al texto, y el encabezado de las páginas. Página 7 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 8. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Figura 2: La primera tabla que se genera, y formatos asignados a sus datos. Página 8 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 9. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Figura 3: Asignar números de página automáticos. Página 9 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 10. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Figura 4: Asignando un ‘Break’, es decir, brinco incondicional a la siguiente página. Página 10 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 11. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Figura 5: Se generó una seguna tabla, con formato para algunos datos. Página 11 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 12. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Figura 6: Se generó un segundo ‘Break’, otro brinco incondicional a la página siguiente. Página 12 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 13. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Figura 7: Se inserta una imagen en el documento, dentro de una tabla (esta, no visible). Página 13 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 14. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Figura 8: Se envía 4 párrafos de texto al documento, con formato ‘right’, ‘left’, ‘center’ y ‘justify’, respectivamente. Página 14 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 15. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Figura 9: Orden de enviar el documento a la impresora. (En este caso, la impresora fue ‘PdfCreator’). Página 15 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 16. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Figura 10: Guardado automático del documento en el folder indicado desde el código C#. Página 16 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 17. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. 4. Primer paso: desde el IDE Visual C# agregar una referencia al proyecto, denominada Microsoft Word xx.x Object Library Para crear un documento Word desde un programa de C# el primer paso consiste en utilizar el botón derecho sobre el nombre del proyecto, y seleccionar agregar referencia Sobre nombre del Proyecto agregamos Referencia. Página 17 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 18. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Luego, elegimos la pestaña COM, y de esta, seleccionamos la biblioteca Microsoft Word xx.xx Object Library. De la pestaña COM, se selecciona Microsoft Word xx.x Object Library. Página 18 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 19. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. 5. Elementos visuales que se insertan en la aplicación. Elementos de arrastrar y pegar en la aplicación. a) Nombre del primer botón insertado (y único): Docto_Word. b) Nombre del segundo y último elemento utilizado: mensaje_de_word. Página 19 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 20. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. 6. Código C# para construir y manipular un documento Word. // Inicia el código. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.Office.Interop.Word; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private Microsoft.Office.Interop.Word.Application ApWord; private Microsoft.Office.Interop.Word.Document doc; private object opc = Type.Missing; // parámetro opcional public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Página 20 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 21. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. ApWord = new Microsoft.Office.Interop.Word.Application(); doc = ApWord.Documents.Add(ref opc, ref opc, ref opc, ref opc); doc.Range(ref opc, ref opc).Delete(ref opc, ref opc); //Visualizar un documento ApWord.Visible = true; // MessageBox.Show("Observar que el nuevo doc. Word no tiene contenido ...", "", MessageBoxButtons.OK, MessageBoxIcon.Information); // ****************************************************************************** // IMPORTANTE: La siguiente asignacion de tipo de letra y su tamaño, afecta a todo el documento Word. // con el mismo 'doc.Content.Font...' no se puede re-asignar nuevos valores, // porque re-afectaría incluso la configuración antes hecha. // Afecta todo el texto que siguira, hasta modificar otra vez estas indicaciones. doc.Content.Font.Name = "Calibri"; doc.Content.Font.Size = 12; doc.Content.InsertAfter("1. Lines: 1, 2 y 3 en 'Calibri', tamaño = 12. n"); // Insertar texto al final del texto del documento Word. doc.Range(ref opc, ref opc).InsertAfter("2. Now, the second text added. n"); doc.Range(ref opc, ref opc).InsertAfter("3. Now, the third text placed. nn"); // ****************************************************************************************************** // ************************************************************************** // ASIGNAR TIPO DE LETRA, Y TAMAÑO AL TEXTO FUNCIONA PERFECTAMENTE.... object EndOfDoc1 = "endofdoc"; Microsoft.Office.Interop.Word.Paragraph oPara1; object Rng1 = doc.Bookmarks.get_Item(ref EndOfDoc1).Range; Rng1 = doc.Bookmarks.get_Item(ref EndOfDoc1).Range; oPara1 = doc.Content.Paragraphs.Add(ref Rng1); Página 21 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 22. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. oPara1.Range.Font.Name = "Lucida Calligraphy"; oPara1.Range.Font.Size = 18; oPara1.Range.Text = "Hecho por M.C. Enrique Ruiz Diaz ...(Lucida Calligraphy a 18)"; oPara1.Range.InsertParagraphAfter(); // Se imprime ya en nuestro documento Word, // porque funciona como variable, su contenido es reemplazado a continuación. doc.Range(ref opc, ref opc).InsertAfter("n"); oPara1.Range.Font.Name = "Courier New"; oPara1.Range.Font.Size = 18; oPara1.Range.Text = "Maestro en Ciencias de la Computaciòn ...(Courier New a 18)"; oPara1.Range.InsertParagraphAfter(); doc.Range(ref opc, ref opc).InsertAfter("n"); // OBSERVACION: Una asignación de tipo de letra y tamaño afecta, persiguiendo, // todo lo demás que siga a continuación. Excepto que se indique nuevas asignaciones. // ************************************************************************** // *************************************************************************************************** // AÑADIR UNA TABLA DE DATOS ... //Insert a 5 x 2 table, fill it with data, and change the column widths. // parte de datos que debo antes tener, segun mis particulares pruebas object oMissing = System.Reflection.Missing.Value; //System.Reflection.Missing.Value; object oEndOfDoc = "endofdoc"; /* endofdoc is a predefined bookmark */ Microsoft.Office.Interop.Word.Table oTable; Microsoft.Office.Interop.Word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = doc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; // asigno tamaño de letra que en general afectara a la siguiente tabla. // excepto cuando se indique otras asignaciones... Página 22 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 23. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. oTable.Range.Font.Size = 12; int r, c; string strText; 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 = ApWord.InchesToPoints(3); //Contrala ancho de la columna - confirmado oTable.Columns[2].Width = ApWord.InchesToPoints(2); ////Contrala ancho de la columna - confirmado // Sin bordes: oTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone; // Sin bordes: oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone; // Poner bordes a la tabla oTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; // Sobre la fila num. 1 ... a Negritas y cursiva sobre los datos .... oTable.Rows[1].Range.Font.Bold = 1; oTable.Rows[1].Range.Font.Italic = 1; oTable.Rows[2].Range.Font.Name = "Bradley Hand ITC"; oTable.Rows[2].Range.Font.Size = 16; double nPrecio = 258123658.39; double nPrecio2 = -10201.78; double nPrecio3 = -15987.89; double nPrecio4 = 31325.49; oTable.Cell(4, 1).Range.Text = provide_format(nPrecio); Página 23 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 24. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. oTable.Cell(4, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; oTable.Cell(3, 2).Range.Text = provide_format(nPrecio2); oTable.Cell(3, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; oTable.Cell(4, 2).Range.Text = provide_format(nPrecio3); // la 'c' indica formato de Moneda oTable.Cell(4,2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(5, 2).Range.Text = provide_format(nPrecio4); oTable.Cell(5, 2).Range.Font.Name = "Calibri"; oTable.Cell(5, 2).Range.Font.Bold = 1; oTable.Cell(5, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; // fin de añadir tabla de datos // NOTA: de acabarse la hoja por el tamaño de la tabla. Word automaticamente // añada una nueva hoja - COMPROBADO! // *************************************************************************************************** // ........................................................................ // Añadir otra cosa después de la Tabla. //Add some text after the table. // *************************************************************************** // FUNCIONÓ INSERTAR UN BREAK, NUEVA PÁGINA EN NUESTRO DOCUMENTO DE WORD // C# word automation : Inserting page break object o_EndOfDoc = "endofdoc"; object paramNextPage = WdBreakType.wdSectionBreakNextPage; //wrdDocument.Bookmarks.get_Item(ref o_EndOfDoc).Range.InsertBreak(ref paramNextPage); Página 24 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 25. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. doc.Bookmarks.get_Item(ref o_EndOfDoc).Range.InsertBreak(ref paramNextPage); oPara1.Range.Font.Name = "Britannic Bold"; oPara1.Range.Font.Size = 14; oPara1.Range.Text = "Yo 'texto' debo salir en una nueva página, dado un 'BREAK' ... 'Britannic Bold' a 14 nn"; oPara1.Range.InsertParagraphAfter(); // *************************************************************************** oPara1.Range.Font.Size = 14; oPara1.Range.Font.Name = "Georgia"; oPara1.Range.Text = "A continuaciòn una tabla de datos grande. Letra: 'Georgia' a 14 nn"; oPara1.Range.InsertParagraphAfter(); // ........................................................................ // AÑADIDR UNA TABLA DE DATOS ... //Insert a 5 x 2 table, fill it with data, and change the column widths. // parte de datos que debo antes tener, segun mis particulares pruebas object oMissing2 = System.Reflection.Missing.Value; object oEndOfDoc2 = "endofdoc"; Microsoft.Office.Interop.Word.Table oTable2; Microsoft.Office.Interop.Word.Range wrdRng2 = doc.Bookmarks.get_Item(ref oEndOfDoc2).Range; wrdRng2 = doc.Bookmarks.get_Item(ref oEndOfDoc2).Range; oTable2 = doc.Tables.Add(wrdRng2, 20, 2, ref oMissing, ref oMissing); oTable2.Range.ParagraphFormat.SpaceAfter = 6; //int r, c; !YA EXPRESADAS ARRIBA //string strText; !YA EXPRESADAS ARRIBA for (r = 1; r <= 20; r++) for (c = 1; c <= 2; c++) { strText = "row = " + r + "column = " + c; Página 25 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 26. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. oTable2.Cell(r, c).Range.Text = strText; } oTable2.Columns[1].Width = ApWord.InchesToPoints(4); oTable2.Columns[2].Width = ApWord.InchesToPoints(2); // Sobre la fila num. 1 ... a Negritas y cursiva sobre los datos .... oTable2.Rows[1].Range.Font.Bold = 1; oTable2.Rows[1].Range.Font.Italic = 1; oTable2.Rows[1].Range.Font.Name = "Bradley Hand ITC"; oTable2.Rows[1].Range.Font.Size = 18; // fin de añadir tabla de datos // NOTA: de acabarse la hoja por el tamaño de la tabla. Word automaticamente // añada una nueva hoja - COMPROBADO! // ........................................................................ //************************************************************************ // FIJANDO MARGENES TODO EL DOCUMENTO WORD. // COMPROBADO - Si el usuario normal de Word altera márgenes, no importa... // porque yo impongo mis márgenes para mi documento aquí creado ... object nothing = System.Reflection.Missing.Value; doc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperLetter; doc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait; doc.PageSetup.TopMargin = 60.0f; // Distancia desde el encabezado hasta el primer texto para todas las hojas - confirmado 57.0f; doc.PageSetup.BottomMargin = 60.0f; // Distancia del ultimo texto en cada hoja, hasta el pie de página - confirmado ... doc.PageSetup.LeftMargin = 80.0f; // Afirmativo: este es para margen izquiedo para todas las hojas generadas... doc.PageSetup.RightMargin = 60.0f; // ... Posible- contrada distancia del margen derecho de cada hoja ... doc.PageSetup.HeaderDistance = 30.0f; // desconozco que controla, pero valor correcto debe ser 30.0f ... //************************************************************************ Página 26 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 27. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. // **************************************************************************************** //How to insert <Current Page> of <Total Pages> into the footer for a MS Word Document in VSTO //Open up the footer in the word document doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter; // Set current Paragraph Alignment to Center doc.ActiveWindow.ActivePane.Selection.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; // Type in 'Page ' doc.ActiveWindow.Selection.TypeText("Page "); // Add in current page field Object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref CurrentPage, ref opc, ref opc); // Type in ' of ' doc.ActiveWindow.Selection.TypeText(" of "); // Add in total page field Object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref TotalPages, ref opc, ref opc); // Add header in the doc doc.Content.Application.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;// = Convert.ToInt32(Word.WdSeekView.wdSeekCurrentPageHeader); doc.Content.Application.Selection.TypeText("M.C. Enrique Ruiz Díaz."); doc.Content.Application.Selection.Fields.Add(doc.Content.Application.Selection.Range, ref opc, ref opc, ref opc); // **************************************************************************************************************** Página 27 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 28. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. // **************************************************************************************** // AÑADIR UNA IMAGEN AL DOCUMENTO ... // Primero creo una tabla de una sola fila y una sola columna para allí poner la imagen. // Se trata ya, de la tercera tabla de mi docto. //****************************************************************************************** // CONOCIMIENTO: NUNCA DEBES GENERAR DOS TABLAS EN FORMA CONSECUTIVA. DEBES SEPARARLO CON // TEXTO. COMO SIGUE A CONTINUACIÒN. SE GENERA ERROR DE NO HACERSE ASI. // TABLA SIGUIENTE 1X1, SOLO PARA LA IMAGEN A AGREGARSE. oPara1.Range.Font.Size = 14; oPara1.Range.Font.Name = "Calibri"; oPara1.Range.Text = "n n n Sigue una tercera tabla con una sola fila y una sola columna. Para IMAGEN ... Letra: 'Calibri' a 14 nn"; oPara1.Range.InsertParagraphAfter(); // Creamos una nueva tabla de 1 x 1 solo para insertar una imagen .... object oMissing3 = System.Reflection.Missing.Value; object oEndOfDoc3 = "endofdoc"; Microsoft.Office.Interop.Word.Table oTable3; Microsoft.Office.Interop.Word.Range wrdRng3 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range; wrdRng3 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range; oTable3 = doc.Tables.Add(wrdRng3, 1, 1, ref oMissing3, ref oMissing3); oTable3.Range.ParagraphFormat.SpaceAfter = 6; //oTable3.Cell(1, 1).Range.Text = "una fila, una columna"; oTable3.Columns[1].Width = ApWord.InchesToPoints(3); // *********************************************************************************** object missing = System.Reflection.Missing.Value; Página 28 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 29. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. object start1 = 0; Range rng = doc.Range(ref start1, ref missing); Range rngPic = doc.Tables[3].Range; rngPic.InlineShapes.AddPicture(@"C:ImagenThe Vision.jpg", ref missing, ref missing, ref missing); // ********************************************************************************************* // *************************************************************************** // RECURRO A UN SEGUDO 'BREAK'. SIGNIFICA UN NUEVO BRINCO DE PAGINA. // C# word automation : Inserting page break object o_EndOfDoc5 = "endofdoc"; object paramNextPage5 = WdBreakType.wdSectionBreakNextPage; //wrdDocument.Bookmarks.get_Item(ref o_EndOfDoc5).Range.InsertBreak(ref paramNextPage5); doc.Bookmarks.get_Item(ref o_EndOfDoc).Range.InsertBreak(ref paramNextPage); oPara1.Range.Font.Name = "Footlight MT Light"; oPara1.Range.Font.Size = 14; oPara1.Range.Text = "Este es un nuevo BREAK (el segundo). Debo salir en una nueva página, dado un 'BREAK' ... 'Footlight MT Light' a 14 nn"; oPara1.Range.InsertParagraphAfter(); // *************************************************************************** // ALINEACION AL CENTRO, A LA IZQUIERA JUSTIFICADO Y A LA DERECHA string var5 = "[right] «You attitude determines your altitude»."; string var6 = "[left] «As a diamond, the English Language is forever»."; string var7 = "[center] «Siempre hay un lugar en la cima»."; Página 29 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 30. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. string var8a = "[justify] «Avoid sugar, salt, white flour products or deserts. "; string var8b = "Avoid soft drinks and candy bars or pastries. "; string var8c = "Feed yourself as you would feed a world class athlete before a competition, "; string var8d = "because in many respects, "; string var8e = "that is what you are before starting work each day»."; Microsoft.Office.Interop.Word.Table oTable5; Microsoft.Office.Interop.Word.Range wrdRng5 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range; wrdRng5 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range; oTable5 = doc.Tables.Add(wrdRng5, 4, 1, ref oMissing3, ref oMissing3); oTable5.Range.ParagraphFormat.SpaceAfter = 6; oTable5.Cell(1, 1).Range.Text = var5; oTable5.Cell(1, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; oTable5.Cell(2, 1).Range.Text = var6; oTable5.Cell(2, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; oTable5.Cell(3, 1).Range.Text = var7; oTable5.Cell(3, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; oTable5.Cell(4, 1).Range.Text = var8a + var8b + var8c + var8d + var8e; oTable5.Cell(4, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify; // ****************************************************************************** //Enviar a la impresora ApWord.ActiveDocument.PrintOut(ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc); String nuevoNombreDoc = @"C:ImagenPoliza_01.docx"; Página 30 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 31. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. object param = nuevoNombreDoc; MessageBox.Show("Requiere IMPRIMIR, primero. Luego pulse aquí ...", "", MessageBoxButtons.OK, MessageBoxIcon.Information); try { //Para guardar los cambios y además, asignar un nombre a nuestro docto. Word. doc.SaveAs(ref param, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc); //Cuando la ventana Word está visible y se cierra. ApWord.Visible = false; ApWord.Quit(ref opc, ref opc, ref opc); ApWord = null; doc = null; mensaje_de_word.Text = "Word se acaba de cerrar, para mi propio docto. No para otro ajeno ..."; } catch { MessageBox.Show("Word no requiere cerrarse, ya está cerrado...", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private string provide_format(double num) { string var_String = string.Format("Order Total: {0:C}", num); //string.Format("{0:#,###.00}", num); string resultado = ""; Página 31 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/
  • 32. C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. for (int i=0; i<var_String.Length; i++) //(int i = var_String.Length-1; i>=0; i--) { if (var_String[i] == '-' || var_String[i] == '0' || var_String[i] == '1' || var_String[i] == '2' || var_String[i] == '3' || var_String[i] == '4' || var_String[i] == '5' || var_String[i] == '6' || var_String[i] == '7' || var_String[i] == '8' || var_String[i] == '9') { resultado = resultado + var_String[i]; } else { if (var_String[i] == '.') { resultado = resultado + ','; } else { if (var_String[i] == ',') { resultado = resultado + '.'; } } // fin del segundo else } // fin del primer else } // fin del for return resultado; } } // de la clase } // del NameSpace // Fin del código. Página 32 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/