Sunteți pe pagina 1din 32

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Daz.

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

Con ttulo y cdula profesional 5632071 en la Maestra en Ciencias de la Computacin. Egresado del Instituto Tecnolgico de Orizaba, Ver. (Mxico).
Pgina 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 Daz.

Acerca de mi.
Titulado en la Maestra en Ciencias en Ciencias de la Computacin, Cdula profesional 5632071. Egresado del Instituto Tecnolgico de Orizaba, Ver., Mxico. Antes, me Titul en la Licenciatura en Informtica, Cdula profesional 4046033. Egresado del Instituto Tecnolgico de Tuxtepec, Oax., Mxico, distinguindome adems, por ser el mejor promedio de mi generacin con 98%. Bien, regresando al tema de mi Ttulo de Maestra en Ciencias de la Computacin, para subrayar que sta, requiri el desarrollo de una TESIS. Otro aspecto muy importante, fue que durante el desarrollo de mi Maestra escrib un ARTICULO, mismo que fue aceptado para publicacin y con mi ponencia en el evento 'Primer Encuentro de Estudiantes en Ciencia de la Computacin - E2C2' ISBN-10:970-36-0404-8 e ISBN-13:978-970-36-0404-3 celebrado en el Instituto Politcnico Nacional, Mxico, D.F. 2007.

Pgina 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 Daz.

Mi Diploma por mi Ponencia en el Instituto Politcnico Nacional, Mxico, D.F. 2007.


Pgina 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 Daz.

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 Daz.
Pgina 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 Daz.

NDICE Acerca de mi. ............................................................................................................................................................. 2 NDICE ........................................................................................................................................................................ 5 1. Lista de objetivos que logra el cdigo C# presentado para la manipulacin de un documento Word. .................. 6 2. Recursos Software utilizados. ................................................................................................................................ 6 3. Secuencia de Imgenes que prueban la creacin y manipulacin de un documento Word, desde cdigo 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 aplicacin. ........................................................................................... 19 6. Cdigo C# para construir y manipular un documento Word. ............................................................................... 20

Pgina 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 Daz.

1. Lista de objetivos que logra el cdigo C# presentado para la manipulacin de un documento Word.
1) Asignar mrgenes a la hoja, para nuestro documento, independientes de mrgenes en Word indicados. 2) Poner encabezado. 3) Poner nmeros de pgina automticos. 4) Mandar texto al documento, asignndole 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 pgina. 9) Enviar texto al documento e imponer alinacin 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 sealado en el cdigo. 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 habra inconveniente que con Visual C# 2010, y Microsoft Word 2010 se logren los mismos resultados.

Pgina 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 Daz.

3. Secuencia de Imgenes que prueban la creacin y manipulacin de un documento Word, desde cdigo C#.

Figura 1: Asignado formato al texto, y el encabezado de las pginas.

Pgina 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 Daz.

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

Pgina 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 Daz.

Figura 3: Asignar nmeros de pgina automticos.

Pgina 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 Daz.

Figura 4: Asignando un Break, es decir, brinco incondicional a la siguiente pgina.

Pgina 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 Daz.

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

Pgina 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 Daz.

Figura 6: Se gener un segundo Break, otro brinco incondicional a la pgina siguiente.

Pgina 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 Daz.

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

Pgina 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 Daz.

Figura 8: Se enva 4 prrafos de texto al documento, con formato right, left, center y justify, respectivamente.

Pgina 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 Daz.

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

Pgina 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 Daz.

Figura 10: Guardado automtico del documento en el folder indicado desde el cdigo C#.

Pgina 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 Daz.

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 botn derecho sobre el nombre del proyecto, y seleccionar agregar referencia

Sobre nombre del Proyecto agregamos Referencia.

Pgina 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 Daz.

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

De la pestaa COM, se selecciona Microsoft Word xx.x Object Library.

Pgina 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 Daz.

5. Elementos visuales que se insertan en la aplicacin.

Elementos de arrastrar y pegar en la aplicacin.

a) Nombre del primer botn insertado (y nico): Docto_Word. b) Nombre del segundo y ltimo elemento utilizado: mensaje_de_word.

Pgina 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 Daz.

6. Cdigo C# para construir y manipular un documento Word.


// Inicia el cdigo.
using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; 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; // parmetro opcional public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) {

Pgina 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 Daz.
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 tamao, afecta a todo el documento Word. // con el mismo 'doc.Content.Font...' no se puede re-asignar nuevos valores, // porque re-afectara incluso la configuracin 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', tamao = 12. \n"); // Insertar texto al final del texto del documento Word. doc.Range(ref opc, ref opc).InsertAfter("2. Now, the second text added. doc.Range(ref opc, ref opc).InsertAfter("3. Now, the third text placed. \n"); \n\n");

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

// ************************************************************************** // ASIGNAR TIPO DE LETRA, Y TAMAO 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);

Pgina 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 Daz.
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 continuacin. 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 Computacin ...(Courier New a 18)"; oPara1.Range.InsertParagraphAfter(); doc.Range(ref opc, ref opc).InsertAfter("\n"); // OBSERVACION: Una asignacin de tipo de letra y tamao afecta, persiguiendo, // todo lo dems que siga a continuacin. Excepto que se indique nuevas asignaciones. // ************************************************************************** // *************************************************************************************************** // AADIR 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 tamao de letra que en general afectara a la siguiente tabla. // excepto cuando se indique otras asignaciones...

Pgina 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 Daz.
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 double double double nPrecio = 258123658.39; nPrecio2 = -10201.78; nPrecio3 = -15987.89; nPrecio4 = 31325.49;

oTable.Cell(4, 1).Range.Text = provide_format(nPrecio);

Pgina 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 Daz.
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 aadir tabla de datos NOTA: de acabarse la hoja por el tamao de la tabla. Word automaticamente aada una nueva hoja - COMPROBADO! ***************************************************************************************************

// ........................................................................ // Aadir otra cosa despus de la Tabla. //Add some text after the table.

// *************************************************************************** // FUNCION INSERTAR UN BREAK, NUEVA PGINA 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);

Pgina 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 Daz.
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 pgina, dado un 'BREAK' ... 'Britannic Bold' a 14 \n\n"; oPara1.Range.InsertParagraphAfter(); // *************************************************************************** oPara1.Range.Font.Size = 14; oPara1.Range.Font.Name = "Georgia"; oPara1.Range.Text = "A continuacin una tabla de datos grande. Letra: 'Georgia' a 14 \n\n"; oPara1.Range.InsertParagraphAfter(); // ........................................................................ // AADIDR 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;

Pgina 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 Daz.
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 aadir tabla de datos // NOTA: de acabarse la hoja por el tamao de la tabla. Word automaticamente // aada una nueva hoja - COMPROBADO! // ........................................................................

//************************************************************************ // FIJANDO MARGENES TODO EL DOCUMENTO WORD. // COMPROBADO - Si el usuario normal de Word altera mrgenes, no importa... // porque yo impongo mis mrgenes 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 pgina 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 ... //************************************************************************

Pgina 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 Daz.

// **************************************************************************************** //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 Daz."); doc.Content.Application.Selection.Fields.Add(doc.Content.Application.Selection.Range, ref opc, ref opc, ref opc); // ****************************************************************************************************************

Pgina 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 Daz.

// **************************************************************************************** // AADIR 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 CONTINUACIN. 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 \n\n"; 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;

Pgina 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 Daz.
object start1 = 0; Range rng = doc.Range(ref start1, ref missing); Range rngPic = doc.Tables[3].Range; rngPic.InlineShapes.AddPicture(@"C:\Imagen\The 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 pgina, dado un 'BREAK' ... 'Footlight MT Light' a 14 \n\n"; 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.";

Pgina 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 Daz.
string string string string string var8a var8b var8c var8d var8e = = = = = "[justify] Avoid sugar, salt, white flour products or deserts. "; "Avoid soft drinks and candy bars or pastries. "; "Feed yourself as you would feed a world class athlete before a competition, "; "because in many respects, "; "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:\Imagen\Poliza_01.docx";

Pgina 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 Daz.
object param = nuevoNombreDoc; MessageBox.Show("Requiere IMPRIMIR, primero. Luego pulse aqu ...", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

try { //Para guardar los cambios y adems, 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 = "";

Pgina 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 Daz.
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 cdigo.

Pgina 32 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

S-ar putea să vă placă și