Word PDF Excel HTML Con C#

45
En este artículo paso a paso se describe cómo crear un nuevo documento en Microsoft Word utilizando automatización desde Microsoft Visual C# 2005 o Microsoft Visual C#. NET. Código de ejemplo El código de ejemplo en este artículo muestra cómo hacer lo siguiente: Insertar párrafos con texto y el formato. Examinar y modificar distintos intervalos dentro de un documento. Insertar tablas, tablas de formato y llenar las tablas con datos. Agregar un gráfico. Para crear un nuevo documento de Word utilizando automatización desde Visual C# 2005 o Visual C#. NET, siga estos pasos: 1. Inicie Microsoft Visual Studio 2005 o Microsoft Visual Studio NET.. 2. En el menú archivo , haga clic en nuevo y, a continuación, haga clic en proyecto . En Tipos de proyecto , haga clic en Proyectos de Visual C# y, después, haga clic en Aplicación para Windows en plantillas . Se creará Form1 de manera predeterminada. Nota En Visual Studio 2005, haga clic en C# en lugar de Proyectos de Visual C# . 3. Agregue una referencia a la Biblioteca de objetos de Microsoft Word . Para ello, siga estos pasos: a. En el menú proyecto , haga clic en Agregar referencia . b. En la ficha COM , busque Microsoft Word Object Library y, a continuación, haga clic en seleccionar . Nota En Visual Studio 2005, no es necesario haga clic en Seleccionar . Nota Microsoft Office 2003 incluye a ensamblados

Transcript of Word PDF Excel HTML Con C#

Page 1: Word PDF Excel HTML Con C#

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

Código de ejemplo

El código de ejemplo en este artículo muestra cómo hacer lo siguiente: Insertar párrafos con texto y el formato. Examinar y modificar distintos intervalos dentro de un documento.

Insertar tablas, tablas de formato y llenar las tablas con datos.

Agregar un gráfico.

Para crear un nuevo documento de Word utilizando automatización desde Visual C# 2005 o Visual C#. NET, siga estos pasos:

1. Inicie Microsoft Visual Studio 2005 o Microsoft Visual Studio NET..2. En el menú archivo , haga clic en nuevo y, a continuación, haga clic en

proyecto . En Tipos de proyecto , haga clic en Proyectos de Visual C# y, después, haga clic en Aplicación para Windows en plantillas . Se creará Form1 de manera predeterminada.

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

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

a. En el menú proyecto , haga clic en Agregar referencia .

b. En la ficha COM , busque Microsoft Word Object Library y, a continuación, haga clic en seleccionar .

Nota En Visual Studio 2005, no es necesario haga clic en Seleccionar .Nota Microsoft Office 2003 incluye a ensamblados de interoperabilidad primarios (PIA). Microsoft Office XP no incluye PIA, pero pueden descargar. Para obtener más información acerca de los PIA de Office XP, haga clic en el número de artículo siguiente para verlo en Microsoft Knowledge Base:

328912  (http://support.microsoft.com/kb/328912/ ) INFORMACIÓN: El PIA de Microsoft Office XP están disponibles para descarga

c. Haga clic en Aceptar en el cuadro de diálogo Agregar referencias para aceptar sus selecciones. Si se le pregunta si desea generar contenedores para las bibliotecas que ha seleccionado, haga clic en Sí .

2. En el menú Ver , elija cuadro de herramientas para mostrar el cuadro de herramientas y, a continuación, agregue un botón a Form1.

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

4. En la ventana código, reemplace el código siguiente

Page 2: Word PDF Excel HTML Con C#

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

con:

private void button1_Click(object sender, System.EventArgs e){object oMissing = System.Reflection.Missing.Value;object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined

bookmark */

//Start Word and create a new document.Word._Application oWord;Word._Document oDoc;oWord = new Word.Application();oWord.Visible = true;oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,

ref oMissing, ref oMissing);

//Insert a paragraph at the beginning of the document.Word.Paragraph oPara1;oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);oPara1.Range.Text = "Heading 1";oPara1.Range.Font.Bold = 1;oPara1.Format.SpaceAfter = 24; //24 pt spacing after

paragraph.oPara1.Range.InsertParagraphAfter();

//Insert a paragraph at the end of the document.Word.Paragraph oPara2;object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);oPara2.Range.Text = "Heading 2";oPara2.Format.SpaceAfter = 6;oPara2.Range.InsertParagraphAfter();

//Insert another paragraph.Word.Paragraph oPara3;oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);oPara3.Range.Text = "This is a sentence of normal text. Now

here is a table:";oPara3.Range.Font.Bold = 0;oPara3.Format.SpaceAfter = 24;oPara3.Range.InsertParagraphAfter();

//Insert a 3 x 5 table, fill it with data, and make the first row//bold and italic.Word.Table oTable;Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref

oEndOfDoc).Range;oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref

oMissing);oTable.Range.ParagraphFormat.SpaceAfter = 6;int r, c;string strText;for(r = 1; r <= 3; r++)

for(c = 1; c <= 5; c++)

Page 3: Word PDF Excel HTML Con C#

{strText = "r" + r + "c" + c;oTable.Cell(r, c).Range.Text = strText;

}oTable.Rows[1].Range.Font.Bold = 1;oTable.Rows[1].Range.Font.Italic = 1;

//Add some text after the table.Word.Paragraph oPara4;oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);oPara4.Range.InsertParagraphBefore();oPara4.Range.Text = "And here's another table:";oPara4.Format.SpaceAfter = 24;oPara4.Range.InsertParagraphAfter();

//Insert a 5 x 2 table, fill it with data, and change the column widths.wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref

oMissing);oTable.Range.ParagraphFormat.SpaceAfter = 6;for(r = 1; r <= 5; r++)

for(c = 1; c <= 2; c++){

strText = "r" + r + "c" + c;oTable.Cell(r, c).Range.Text = strText;

}oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change

width of columns 1 & 2oTable.Columns[2].Width = oWord.InchesToPoints(3);

//Keep inserting text. When you get to 7 inches from top of the//document, insert a hard page break.object oPos;double dPos = oWord.InchesToPoints(7);oDoc.Bookmarks.get_Item(ref

oEndOfDoc).Range.InsertParagraphAfter();do{

wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;wrdRng.ParagraphFormat.SpaceAfter = 6;wrdRng.InsertAfter("A line of text");wrdRng.InsertParagraphAfter();oPos = wrdRng.get_Information

(Word.WdInformation.wdVerticalPositionRelativeToPage);}while(dPos >= Convert.ToDouble(oPos));object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;object oPageBreak = Word.WdBreakType.wdPageBreak;wrdRng.Collapse(ref oCollapseEnd);wrdRng.InsertBreak(ref oPageBreak);wrdRng.Collapse(ref oCollapseEnd);wrdRng.InsertAfter("We're now on page 2. Here's my chart:");wrdRng.InsertParagraphAfter();

//Insert a chart.Word.InlineShape oShape;object oClassType = "MSGraph.Chart.8";wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

Page 4: Word PDF Excel HTML Con C#

oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing,

ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing);

//Demonstrate use of late bound oChart and oChartApp objects to//manipulate the chart object with MSGraph.object oChart;object oChartApp;oChart = oShape.OLEFormat.Object;oChartApp = oChart.GetType().InvokeMember("Application",

BindingFlags.GetProperty, null, oChart, null);

//Change the chart type to Line.object[] Parameters = new Object[1];Parameters[0] = 4; //xlLine = 4oChart.GetType().InvokeMember("ChartType",

BindingFlags.SetProperty,null, oChart, Parameters);

//Update the chart image and quit MSGraph.oChartApp.GetType().InvokeMember("Update",

BindingFlags.InvokeMethod, null, oChartApp, null);oChartApp.GetType().InvokeMember("Quit",

BindingFlags.InvokeMethod, null, oChartApp, null);//... If desired, you can proceed from here using the Microsoft

Graph //Object model on the oChart and oChartApp objects to make

additional//changes to the chart.

//Set the width of the chart.oShape.Width = oWord.InchesToPoints(6.25f);oShape.Height = oWord.InchesToPoints(3.57f);

//Add text after the chart.wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;wrdRng.InsertParagraphAfter();wrdRng.InsertAfter("THE END.");

//Close this form.this.Close();

}

8. Desplácese hasta la parte superior de la ventana de código. Agregue la siguiente línea al final de la lista de directivas using :

9. using Word = Microsoft.Office.Interop.Word;10. using System.Reflection;

11. Presione F5 para generar y ejecutar el programa.12. Haga clic en Button1 para iniciar la automatización de Word y crear el

documento.

Una vez completado el código, examinar el documento que se ha creado para usted. El documento contiene dos páginas de párrafos con formato, tablas y un gráfico.

Utilizar una plantilla

Page 5: Word PDF Excel HTML Con C#

Si utiliza Automatización para crear documentos que están todas en un formato común, puede beneficiarse de iniciar el proceso con un documento nuevo que se basa en una plantilla con formato previo. Uso una plantilla con el cliente de automatización de Word tiene dos ventajas importantes sobre la creación de un documento desde nada:

Puede tener mayor control sobre el formato y selección de ubicación de objetos a través de los documentos.

Puede crear sus documentos con menos código.

Utilizando una plantilla, puede ajustar selección de ubicación de tablas, párrafos y otros objetos dentro del documento, así como incluir formato en esos objetos. Mediante la automatización, puede crear un nuevo documento basándose en su plantilla con código such as lo siguiente: object oTemplate = "c:\\MyTemplate.dot";oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing,

ref oMissing, ref oMissing);

en su plantilla, pueden definir marcadores por lo que la automatización en el cliente puede rellenar texto variable en una ubicación específica en el documento, como sigue: object oBookMark = "MyBookmark";oDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";

otra ventaja de utilizar una plantilla es que puede crear y almacenar los estilos de formato que desea aplicar en tiempo de ejecución, como sigue: object oStyleName = "MyStyle";oDoc.Bookmarks.Item(ref oBookMark).Range.set_Style(ref oStyleName);

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

1. Development Tools Used

    Microsoft Visual Studio 2005    Microsoft Word 2003    Programming Language: C#

2.  Word Automation using C#:

Word Automation through C# is all about programmatically generating the Word Document using C# code. Working on Word is considered to be straightforward, but doing the same programmatically gets a little intricate. Word automation almost completely involves working with objects and reference types. Almost all of the tasks which we perform on word 2003 can be done programmatically using C# or VB. Tasks like Inserting Table of Contents, Linking documents, Mail Merge, Inserting Documents, Embedding documents, inserting pictures, watermark... etc can all be done programmatically. 

3. Setting Up Work Environment:

Page 6: Word PDF Excel HTML Con C#

Starting off, the first step is to include the Word dll's to the Solution. This can be done by right clicking the Reference Folder in the Solution explorer of the project and select Add Reference.

 

Figure 1. Browse Through the available COM objects and Select Microsoft Office 11.0 Object Library & Microsoft Word 11.0 Object Library. This DLL has all the methods which we do to perform the automation.

Note: This dll would be present only if Microsoft Office is installed on the Machine. Also include "using Microsoft.Office;" in the Namespaces used.

 

Page 7: Word PDF Excel HTML Con C#

Figure 2.

 

Figure 3.

4. Objects Used in Automation:

All the methods used Word automation is derived either from Word.Application or Word.Document class. Let's consider that we want to create a document using the Word Application, we might end up doing the following steps, 

1. Open Word Application. (Opening Word Application creates a new document by default, but in Automation, wee need to manually add a document)

2. Add a New document. 3. Edit the document. 4. Save it.

The same steps needs to be done programmatically. The Word.Application and Word.Document are used to Open Word and add a new Document to it.

4.1 Word.Application:

This represents in Word Application without any new document loaded in it. This is like the base class which is needed to create a new document. Creating a new instance of Word.Application can be visualized as below. 

Page 8: Word PDF Excel HTML Con C#

 

Figure 4. 4.2 Word.Document:

If we need to add a new document file, first we have to create an instance of the Word.Document object and then add it to the Word.Application.

//OBJECT OF MISSING "NULL VALUE"Object oMissing = System.Reflection.Missing.Value();//OBJECTS OF FALSE AND TRUEObject oTrue = true;Object oFalse = false;        //CREATING OBJECTS OF WORD AND DOCUMENTWord.Application oWord = new Word.Application();Word.Document oWordDoc = new Word.Document(); //MAKING THE APPLICATION VISIBLEoWord.Visible = true;        //ADDING A NEW DOCUMENT TO THE APPLICATIONoWordDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

This triggers the following operation in the Word Application 

Page 9: Word PDF Excel HTML Con C#

 

Figure 5.

Approaches to Perform Automation

1. We can either have a base template (.dot) file and open the base template file and work on it.

2. We can otherwise build a word document from scratch.  4.3 Standard Input Parameters:

Most of the methods have input parameters which are of reference type, and the values are mostly true, false or missing (null). In automation it makes sense as to why most of the input parameters are of reference types; it might be because of the fact that most of the methods a multitude of input parameters (many have more than 10 input parameters) and their value is going to be either true, false or missing in most of the cases. So instead of supplying the same input parameter ten times, we can make all the input parameters point to the location same single variable in them memory. 

4.3.1 Range Object:

While we work on Word Application, if we want to type some text in the 11th line, then we manually take the cursor and click it on the required line and then start typing. In order to do the same task, we use the Range variable in C#. The range variable of the Word.Document object represents the location of the cursor on the current document.

There are many possible ways to point to a specific location on a document. I had extensively used the Bookmarks locators as I work on Automation using a base template. In this approach, we insert Bookmarks on the base template and we programmatically locate those Bookmarks, set the range on them and insert text or documents at that specific location. There are also many other possible ways to set the range.

//SETTING THE RANGE ON THE BOOKMARKObject oBookMarkName = "My_Inserted_Bookmark_On_Template";

Page 10: Word PDF Excel HTML Con C#

Word.Range wrdRange = oWordDoc.Bookmarks.get_Item(ref oBookMarkName).Range.Select();

4.3.2 Selection Object:

While working on word, we select a range of text by clicking and dragging the mouse pointer across contents in the document to select it. The contents can be text, formatted text, tables or any other item in the document. We programmatically represent the same by using the Selection Object derived from Word.Selection. In the previous range example, we locate a bookmark and set the range on that specific bookmark and we select it. Now the selection object represents that specific location. It's like placing the cursor on that specific bookmark location on the document. The selection across text can be done by selecting a range of text in between two ranges. Then the selected range can be copied, deleted or formatted.

4.3.3 Selecting Between Bookmarks:

//BOOK MARK FOR START OF SELECTIONObject oBookmarkStart = "BookMark__Start";Object oRngoBookMarkStart = oWordDoc.Bookmarks.get_Item(ref oBookmarkDesignInfoStart).Range.Start; //BOOK MARK FOR END OF SELECTIONObject oBookmarkEnd = "BookMark__End";Object oRngoBookMarkEnd = oWordDoc.Bookmarks.get_Item(ref oBookmarkDesignInfoEnd).Range.Start; //SETTING THE RANGE ON THE BOOKMARK BETWEEN TWO BOOKMARKSWord.Range rngBKMarkSelection = oWordDoc.Range(ref oRngoBookMarkStart, ref oRngoBookMarkEnd); //SELECTING THE TEXTrngBKMarkSelection.Select();rngBKMarkSelection.Delete(ref oMissing, ref oMissing);5. Automation using a Base Template: The base template file method is preferable as it gives us much more flexibility in performing the automation and it comes very handy for performing Mail Merge.  In the base template method, when we call the Documents.Add method of the Application object, we give the path of the .dot file.

//THE LOCATION OF THE TEMPLATE FILE ON THE MACHINEObject oTemplatePath = "C:\\Program Files\\MyTemplate.dot"; //ADDING A NEW DOCUMENT FROM A TEMPLATEoWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

Now .dot file is opened and when we save the generated document, we save it as a new file. 

6. Mail Merge

Mail merge is a useful tool in scenarios where we want to randomly generate alike documents where just a few fields change. For instance in a pay slip which has a

Page 11: Word PDF Excel HTML Con C#

base template and just the employee name, number and pay details needs to change for each employee. Now we can have a base template which is a word file saved as Document Template file.  In the .dot file, insert a Mail Merge Field manually by placing the cursor in the required position and Insert -> Field, and in Field Names, select "MergeField", now the Mail merged field would be represented by <<FieldName>>. The template can be like Contact Information For further information and discussions, please contact:

Name: <<CIFLName>>

Address: <<CIAddress>>

Phone:  <<CIPhW>> (Work)

           <<CIPhM>> (Cell)

Fax:      <<CIFax>>

Email    <<CIMail>>

Now for programmatically replacing the Mail Merge fields using the code, the document by default has many fields in it. But the user entered fields comes with a prefix and suffix which can be can be used as an identifier to replace the fields.

//OBJECT OF MISSING "NULL VALUE"Object oMissing = System.Reflection.Missing.Value(); //OBJECTS OF FALSE AND TRUEObject oTrue = true;Object oFalse = false; //CREATING OBJECTS OF WORD AND DOCUMENTWord.Application oWord = new Word.Application();Word.Document oWordDoc = new Word.Document(); //SETTING THE VISIBILITY TO TRUEoWord.Visible = true; //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINEObject oTemplatePath = "C:\\Program Files\\MyTemplate.dot"; //ADDING A NEW DOCUMENT FROM A TEMPLATEoWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); foreach (Word.Field myMergeField in oWordDoc.Fields){    iTotalFields++;    Word.Range rngFieldCode = myMergeField.Code;    String fieldText = rngFieldCode.Text;     // ONLY GETTING THE MAILMERGE FIELDS    if (fieldText.StartsWith(" MERGEFIELD"))    {        // THE TEXT COMES IN THE FORMAT OF         // MERGEFIELD  MyFieldName  \\* MERGEFORMAT        // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"

Page 12: Word PDF Excel HTML Con C#

        Int32 endMerge = fieldText.IndexOf("\\");        Int32 fieldNameLength = fieldText.Length - endMerge;        String fieldName = fieldText.Substring(11, endMerge - 11);         // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE        fieldName = fieldName.Trim();         // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//        // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE        if (fieldName == "MyField")        {            myMergeField.Select();            oWord.Selection.TypeText("This Text Replaces the Field in the Template");        }    }} There is one other method for replacing the Merge Fields which is mentioned in msdn, which uses a rather memory hungry approach. In that method a separate document is opened and it is inserted with a table which has first row as the Mail Merge Field Name and the second row as the replacement value, then the value from the table is matched with that of the original document and replacement occurs and the second document is purged.

7. Embedding a Document:

Embedding a document is done through the application by Insert-> Object-> Create from file-> Select the File-> Display as Icon. This embeds the file in the selected location as an icon and the user can double click on the icon to open the file. The same can be done through automation.

The range supposed to set at the required place and the same has to be selected (range can be set by any of the means mentioned above). Now with the selection, the file can be embedded.

//ICON LABEL CAN BE THE NAME OF THE FILE, //ITS THE NAME DISPLAYED BESIDES THE EMBEDDED DOCUMENTObject oIconLabel = "File Name"; //INCASE WE NEED THE EMBEDDED DOCUMENT TO BE DISPLAYED AS A SPECIFIC ICON,//WE NEED TO SPECIFY THE LOCATION OF THE ICON FILE//ELSE SET IT TO oMissing VALUEObject oIconFileName = "C:\\Document and Settings\\IconFile.ico"; //THE BOOKMARK WHERE THE FILE NEEDS TO BE EMBEDDEDObject oBookMark = "My_Custom_BookMark";//THE LOCATION OF THE FILEObject oFileDesignInfo = "C:\\Document and Settings\\somefile.doc"; //OTHER VARIABLESObject oClassType = "Word.Document.8";Object oTrue = true;Object oFalse = false;Object oMissing = System.Reflection.Missing.Value; //METHOD TO EMBED THE DOCUMENT

Page 13: Word PDF Excel HTML Con C#

oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.InlineShapes.AddOLEObject(    ref oClassType,ref oFileDesignInfo,ref oFalse, ref oTrue, ref oIconFileName,     ref oMissing,ref oIconLabel, ref oMissing);

8. Inserting a Document File:

Contents of a Word documents can also be inserted into the current document from the application by doing the following. Insert -> File -> Select the File. This extracts the contents from the selected file and inserts it into the current document. In automation, we need to follow a similar approach by placing the range at the required point and selecting it and then inserting the file.

//THE LOCATION OF THE FILEString oFilePath = "C:\\Document and Settings\\somefile.doc";oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.InsertFile(oFilePath,ref oMissing, ref oFalse, ref oFalse, ref oFalse);

 9. Including Water Marks/Pictures in the Document Background:

Including watermarks is one other important feature for any official documents as the watermark may have the company's logo, draft logo or any other picture/text. This is useful when we want a picture or some text to be present throughout the document in the background.

We insert a watermark in the application by performing the following tasks. Format -> Background -> Printed Watermarks The same can also be done programmatically; moreover as we manually define the values like the angle of tilt and actual location of the watermark, we have more flexibility in defining the exact location of the watermark.

9.1 Embedding Pictures in Document Header:  //EMBEDDING LOGOS IN THE DOCUMENT//SETTING FOCUES ON THE PAGE HEADER TO EMBED THE WATERMARKoWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader; //THE LOGO IS ASSIGNED TO A SHAPE OBJECT SO THAT WE CAN USE ALL THE//SHAPE FORMATTING OPTIONS PRESENT FOR THE SHAPE OBJECTWord.Shape logoCustom = null; //THE PATH OF THE LOGO FILE TO BE EMBEDDED IN THE HEADERString logoPath = "C:\\Document and Settings\\MyLogo.jpg";logoCustom = oWord.Selection.HeaderFooter.Shapes.AddPicture(logoPath,    ref oFalse, ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); logoCustom.Select(ref oMissing);logoCustom.Name = "CustomLogo";

Page 14: Word PDF Excel HTML Con C#

logoCustom.Left = (float)Word.WdShapePosition.wdShapeLeft; //SETTING FOCUES BACK TO DOCUMENToWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

9.2 Inserting Text in the Centre of the Document as Water Mark: //THE LOGO IS ASSIGNED TO A SHAPE OBJECT SO THAT WE CAN USE ALL THE//SHAPE FORMATTING OPTIONS PRESENT FOR THE SHAPE OBJECTWord.Shape logoWatermark = null; //INCLUDING THE TEXT WATER MARK TO THE DOCUMENTlogoWatermark = oWord.Selection.HeaderFooter.Shapes.AddTextEffect(    Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,    "Enter The Text Here", "Arial", (float)60,     Microsoft.Office.Core.MsoTriState.msoTrue,     Microsoft.Office.Core.MsoTriState.msoFalse,    0, 0, ref oMissing); logoWatermark.Select(ref oMissing);logoWatermark.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;logoWatermark.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;logoWatermark.Fill.Solid();logoWatermark.Fill.ForeColor.RGB = (Int32)Word.WdColor.wdColorGray30;logoWatermark.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;logoWatermark.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin;logoWatermark.Left = (float)Word.WdShapePosition.wdShapeCenter;logoWatermark.Top = (float)Word.WdShapePosition.wdShapeCenter;logoWatermark.Height = oWord.InchesToPoints(2.4f);logoWatermark.Width = oWord.InchesToPoints(6f); //SETTING FOCUES BACK TO DOCUMENToWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

9.3 Inserting Text in the Centre of Page, and rotating it by 90 Degrees:

//INSERTING TEXT IN THE CENTRE RIGHT, TILTED AT 90 DEGREESWord.Shape midRightText;midRightText = oWord.Selection.HeaderFooter.Shapes.AddTextEffect(    Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,    "Text Goes Here", "Arial", (float)10,     Microsoft.Office.Core.MsoTriState.msoTrue,     Microsoft.Office.Core.MsoTriState.msoFalse,    0, 0, ref oMissing); //FORMATTING THE SECURITY CLASSIFICATION TEXTmidRightText.Select(ref oMissing);midRightText.Name = "PowerPlusWaterMarkObject2";midRightText.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;midRightText.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;midRightText.Fill.Solid();midRightText.Fill.ForeColor.RGB = (int)Word.WdColor.wdColorGray375; //MAKING THE TEXT VERTICAL & ALIGNINGmidRightText.Rotation = (float)90;

Page 15: Word PDF Excel HTML Con C#

midRightText.RelativeHorizontalPosition =     Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;midRightText.RelativeVerticalPosition =     Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin;midRightText.Top = (float)Word.WdShapePosition.wdShapeCenter;midRightText.Left = (float)480;

10. Including Page Numbers in Page Footer:

Including auto-generated page numbers in the Footer is yet another useful feature which can be simulated in the code.

//SETTING THE FOCUES ON THE PAGE FOOTERoWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter; //ENTERING A PARAGRAPH BREAK "ENTER"oWord.Selection.TypeParagraph(); String docNumber = "1";String revisionNumber = "0"; //INSERTING THE PAGE NUMBERS CENTRALLY ALIGNED IN THE PAGE FOOTERoWord.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;oWord.ActiveWindow.Selection.Font.Name = "Arial";oWord.ActiveWindow.Selection.Font.Size = 8;oWord.ActiveWindow.Selection.TypeText("Document #: " + docNumber + " - Revision #: " + revisionNumber); //INSERTING TAB CHARACTERSoWord.ActiveWindow.Selection.TypeText("\t");oWord.ActiveWindow.Selection.TypeText("\t"); oWord.ActiveWindow.Selection.TypeText("Page ");Object CurrentPage = Word.WdFieldType.wdFieldPage;oWord.ActiveWindow.Selection.Fields.Add(oWord.Selection.Range, ref CurrentPage, ref oMissing, ref oMissing);oWord.ActiveWindow.Selection.TypeText(" of ");Object TotalPages = Word.WdFieldType.wdFieldNumPages;oWord.ActiveWindow.Selection.Fields.Add(oWord.Selection.Range, ref TotalPages, ref oMissing, ref oMissing); //SETTING FOCUES BACK TO DOCUMENToWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

11. Basic Text Formatting Options:

11.1 Paragraph Break:

This is equivalent to hitting the enter button in the document.

//ENTERING A PARAGRAPH BREAK "ENTER"oWord.Selection.TypeParagraph();

Page 16: Word PDF Excel HTML Con C#

11.2 Text Formatting Option:

All the text formatting options available in the Word Application can also be replicated through automation.

//OTHER COMMONLY USED FORMATTING OPTIONSoWord.Selection.Font.Bold = 1;oWord.Selection.Font.Color = Word.WdColor.wdColorAqua;oWord.Selection.Font.Italic = 1;oWord.Selection.Font.Underline = Word.WdUnderline.wdUnderlineDashHeavy;

11.3 Clear Formatting:

When the Formatting is applied to a selection, then the same formatting gets carried on to the next lines, in order to clear the formatting, the next line needs to be selected and ClearFormatting() method needs to be called.

//CLEARING THE FORMATTINGoWord.Selection.ClearFormatting();

12. Table of Contents:

Table of Contents is very handy when it comes to official documents or some technical papers which span across many pages. Table of contents can be inserted and updated on the fly as the document gets built.  For the Table of Contents to get auto generated without any hassles, it is vital that the Headings, Sub-Headings and the Body text have their respective attributes set. When we work on the application, the values get set by themselves, we only need to edit if required. But while programming its mandatory that we set the values in the code in order to prevent any anomalies when the Table of Contents gets updated.  Below is an example of a document which was programmatically generated.

Page 17: Word PDF Excel HTML Con C#

Figure 6. It is apparent that the Header 2 and Header 3 and Body are formatted differently and even in the Table of Contents the Header 2 is slightly offset from the Header 1. Open the above document and Outlining Tool bar, View -> Toolbars -> Outlining. And on moving the cursor on the Sample Header 2, we can see that the Format is Heading 2 and Outlining level is Level 2. 

Figure 7.

And for Body, the Format is Normal + Arial, 10 pt and Outlining Level is Body text.

 

Figure 8.

The same values needs to be set programmatically for the Table of Contents to get generated.

12.1 Section Format:

Page 18: Word PDF Excel HTML Con C#

For setting the Format of the Selection, select the entire text (select between bookmarks like mentioned before in Selection section) and set the value

//SETTING THE FORMAT TYPE//SELECT THE CONTENST TO BE FORMATTED AND SET THE VALUE Object styleHeading2 = "Heading 2";Object styleHeading3 = "Heading 3"; oWord.Selection.Range.set_Style(ref styleHeading2);oWord.Selection.Range.set_Style(ref styleHeading3);

12.2 Outline Level:

For setting the outline level, select the contents and set it to one of the values mentioned below

//SETTING THE OUTLINE LEVEL//SELECT THE CONTENTS WHOSE OUTLINE LEVEL NEEDS TO BE CHANGED AND//SET THE VALUE oWord.Selection.Paragraphs.OutlineLevel =Word.WdOutlineLevel.wdOutlineLevel2;                                          oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel3;        oWord.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevelBodyText;                                

12.3   Inserting Table of Contents:

Once the Outline Levels & Section Style are set, the Table of Contents can be inserted programmatically and the page numbers gets populated automatically based on the Outline Levels & Section Style set by the user. (Also refer this MSDN Link)

// NAME OF THE BOOKMARK IN THE DOCUMENT (.dot Template) WHERE TABLE OF // CONTENTS NEEDS TO BE ADDEDObject oBookmarkTOC = "Bookmark_TOC"; // SETTING THE RANGE AT THE BOOKMARKWord.Range rngTOC = oWordDoc.Bookmarks.get_Item(ref oBookmarkTOC).Range; // SELECTING THE SET RANGErngTOC.Select(); // INCLUDING THE TABLE OF CONTENTSObject oUpperHeadingLevel = "1";Object oLowerHeadingLevel = "3";Object oTOCTableID = "TableOfContents";oWordDoc.TablesOfContents.Add(rngTOC, ref oTrue, ref oUpperHeadingLevel,    ref oLowerHeadingLevel,ref oMissing, ref oTOCTableID, ref oTrue,    ref oTrue, ref oMissing, ref oTrue, ref oTrue, ref oTrue);

12.4 Updating Table of Contents:

Page 19: Word PDF Excel HTML Con C#

Usually the Table of Contents is inserted in the beginning of the document generation and once all the contents are populated, the locations of the Headings and Sub Headings tend to change. If the Table of Contents is not updated, then its contents points to different pages. To overcome this hassle, the Table of Contents needs to be updated at the end of the Automation.

//UPDATING THE TABLE OF CONTENTSoWordDoc.TablesOfContents[1].Update(); //UPDATING THE TABLE OF CONTENTSoWordDoc.TablesOfContents[1].UpdatePageNumbers();

13. Saving/Closing & Re-Opening the File:

13.1 Saving the File: //THE LOCATION WHERE THE FILE NEEDS TO BE SAVEDObject oSaveAsFile = (Object)"C:\\SampleDoc.doc"; oWordDoc.SaveAs(ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,     ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing,     ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,    ref oMissing, ref oMissing);

13.2 Closing the File:

//CLOSING THE FILEoWordDoc.Close(ref oFalse, ref oMissing, ref oMissing); //QUITTING THE APPLICATIONoWord.Quit(ref oMissing, ref oMissing, ref oMissing);

13.3 Re-Opening the File:

The Open () method which we use in Word2003 dll might throw an exception if the client have another version of word installed in their machine. If the client has Word 2002, then he has to open a word file only by Open2002 () method. Open () method which comes for Word 2003 might through an exception in Word 2002 environment. And for Word 2000, there is a method called Open2000 () and Open2002 () for Office 2002 and so on. So it is wise to put the Open () in a try-catch block as mentioned below.

Figure 10.

14. Tips for Word Automation to Create New Document (Non-Base Template Approach)

(Refer to this MSDN link)When we proceed to create a New Document without using the Base Template, the most useful entity is the inbuilt Bookmark endofdoc. It would be a build-from-

Page 20: Word PDF Excel HTML Con C#

scratch approach where the programmer starts of the automation by inserting his first section of contents, then setting the range to point to the endofdoc Bookmark and selecting it and inserting his contents and again selecting the endofdoc which would be pointing to the end of the document which would now be after the two sections.

Exportar a PDF, Excel y Otros formatos en C# (DataGridView & Windows Forms).

Hola, en esta ocasión les traigo un ejemplo de como exportar los datos de un dataGridView (en WinForms) a diversos formatos sin la necesidad de interactuar con componentes ActiveX y tampoco de utilizar la interoperabilidad de Office.

En el caso de utilizar PDF si utilice una librería llamada iTextSharp y para los demás es solo programación, pero eso lo veremos un poco mas adelante.

Este ejemplo muestro un programa que tiene un dataGridView en el que se muestran los datos que se llenan desde una base de datos y esa información es la que se exporta a diferentes formatos. En esta entrada no explico como se llena el dataGridView porque hay muchas formas de hacerlo y me imagino que eso no les interesa. Habiendo quedando claro eso comencemos con el ejemplo.

Exportando a PDF

Para la exportación de los datos del dataGridView a PDF estoy utilizando una librería muy interesante llamada iTextSharp que es un "Port" de otra librería llamada iText para Java solo que esta es para C#. Al estar utilizando esta librería me sorprendió de una forma muy grata ya que no la conocía. esta puede ser una opción a crystal reports al momento de hacer reportes principalmente si es que no deseas que tu aplicación eleve considerablemente su tamaño y su rendimiento, eso si es mucho mas trabajo porque todo es por código y no puedes diseñar tus reportes de una forma visual aunque con un poco de dedicación puedes sacar PDF’s muy completos en cuanto a diseño ya que esta librería te provee de muchas clases para diseñar el PDF conforme a tus necesidades (Para mas información sobre iTextSharp visiten este pagina http://itextsharp.sourceforge.net/ ), pero bueno no me quiero meter tanto en esto y continuemos con el ejemplo.

Primero que nada creamos un Nuevo proyecto del Tipo WidowsApplication en Visual Studio y agregamos una referencia a la DLL de iTextSharp (descargar DLL iTextSharp) en nuestro proyecto.

Page 21: Word PDF Excel HTML Con C#

Agregamos la dll de iTextSharp nuestro proyecto.

Una vez teniendo agregada la DLL diseñamos un WindowsForm como en la siguiente imagen agregamos un botón al que le pondremos “Exportar ” y accedemos a su evento Onclick.

En este ejemplo tendremos estos datos y los exportaremos a PDF usando ItextSharp.

Antes de poner el código es necesario agregar los siguientes espacios de nombres entre otros:

using iTextSharp.text;using iTextSharp.text.pdf;

//Código para exportar DataGridView a PDF usando iTextSharp

//Evento clic del Botón Exportar

Page 22: Word PDF Excel HTML Con C#

private void Exportar_pdf(object sender, EventArgs e)

{

try

{

Document doc = new Document(PageSize.A4.Rotate(), 10, 10

,10, 10);

string filename = "DataGridViewTest.pdf";

FileStream file = new FileStream(filename,

FileMode.OpenOrCreate,

FileAccess.ReadWrite,

FileShare.ReadWrite);

PdfWriter.GetInstance(doc, file);

doc.Open();

GenerarDocumento(doc);

doc.Close();

Process.Start(filename);

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

//Función que genera el documento Pdf

public void GenerarDocumento(Document document)

{

//se crea un objeto PdfTable con el numero de columnas del

//dataGridView

PdfPTable datatable = new PdfPTable(dataGridView1.ColumnCount);

Page 23: Word PDF Excel HTML Con C#

//asignamos algunas propiedades para el diseño del pdf datatable.DefaultCell.Padding = 3;

float[] headerwidths = GetTamañoColumnas(dataGridView1);

datatable.SetWidths(headerwidths);

datatable.WidthPercentage = 100;

datatable.DefaultCell.BorderWidth = 2;

datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

//SE GENERA EL ENCABEZADO DE LA TABLA EN EL PDF

for (int i = 0; i < dataGridView1.ColumnCount; i++)

{

datatable.AddCell(dataGridView1.Columns[i].HeaderText);

}

datatable.HeaderRows = 1;

datatable.DefaultCell.BorderWidth = 1;

//SE GENERA EL CUERPO DEL PDF

for (int i = 0; i < dataGridView1.RowCount; i++)

{

for (int j = 0; j < dataGridView1.ColumnCount; j++)

{

datatable.AddCell(dataGridView1[j, i].Value.ToString());

}

datatable.CompleteRow();

}

//SE AGREGAR LA PDFPTABLE AL DOCUMENTO

Page 24: Word PDF Excel HTML Con C#

document.Add(datatable);

}

 

//Función que obtiene los tamaños de las columnas del gridpublic float[] GetTamañoColumnas(DataGridView dg){ float[] values = new float[dg.ColumnCount]; for (int i = 0; i < dg.ColumnCount; i++) { values[i] = (float)dg.Columns[i].Width; } return values;}  

Imagen del Pdf generado en este ejemplo.

Nota: Este ejemplo esta hecho para Windows Forms para el componente DataGridView pero para ASP.net seria muy similar para el componente DataGrid solo que manejando con mucho cuidado los paths.

Exportando a otros formatos

Page 25: Word PDF Excel HTML Con C#

diseño de la forma para exportar a otros formatos en este ejemplo

 

Exportando A Excel

Para la exportación a este formato es una pequeña trampita si es que se puede llamar así porque lo que se esta haciendo es generar un documento con código HTML pero guardarlo con extensión XLS!!!, en donde simplemente los datos que tenemos en el Grid lo pasamos a una tabla HTML y ya con eso tendremos nuestros datos exportados a Excel .

El siguiente código es una clase llamada “OtrosFormatos” la cual tiene 2 métodos los cuales son “Export” y “ExportCSV” este ultimo para exportar al formato CSV además de contar con 2 atributos los cuales son el “StreamWriter” (clase del NameSpace System.IO) y la ruta en donde queremos guardar el archivo.

clase OtrosFormatos

public class OtrosFormatos

{

StreamWriter w;

string ruta;

public string xpath { get { return ruta; } set { value = ruta; }}

/// <summary>

/// Constructor que establece el path del archivo

/// </summary>

Page 26: Word PDF Excel HTML Con C#

/// <param name="path"></param>

public OtrosFormatos(string path)

{

ruta = @path;

}

 

/// <summary>

/// Exporta datos a un archivo

/// </summary>

/// <param name="titulos"></param>

/// <param name="datos"></param>

public void Export(ArrayList titulos, DataTable datos)

{

try

{

FileStream fs = new FileStream(ruta, FileMode.Create,

FileAccess.ReadWrite);

w = new StreamWriter(fs);

string comillas = char.ConvertFromUtf32(34);

StringBuilder html = new StringBuilder();

html.Append(@"<!DOCTYPE html PUBLIC" + comillas +

"-//W3C//DTD XHTML 1.0 Transitional//EN" + comillas +

" " + comillas

+ http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd

+ comillas + ">");

html.Append(@"<html xmlns=" + comillas

+ http://www.w3.org/1999/xhtml

+ comillas + ">");

Page 27: Word PDF Excel HTML Con C#

html.Append(@"<head>");

html.Append(@"<meta http-equiv=" + comillas +"Content-Type"

+ comillas + "content=" + comillas

+ "text/html; charset=utf-8" + comillas+"/>");

html.Append(@"<title>Untitled Document</title>");

html.Append(@"</head>");

html.Append(@"<body>");

 

//Generando encabezados del archivo

//(aquí podemos dar el formato como a una tabla de HTML)

html.Append(@"<table WIDTH=730 CELLSPACING=0 CELLPADDING=10

border=8 BORDERCOLOR=" + comillas + "#333366"

+ comillas + " bgcolor=" + comillas + "#FFFFFF"

+ comillas + ">");

html.Append(@"<tr> <b>");

foreach (object item in titulos)

{

html.Append(@"<th>" + item.ToString() + "</th>");

}

html.Append(@"</b> </tr>");

//Generando datos del archivo

for (int i = 0; i < datos.Rows.Count; i++)

{

html.Append(@"<tr>");

for (int j = 0; j < datos.Columns.Count; j++)

{

Page 28: Word PDF Excel HTML Con C#

html.Append(@"<td>" +

datos.Rows[i][j].ToString() + "</td>");

}

html.Append(@"</tr>");

}

html.Append(@"</body>");

html.Append(@"</html>");

w.Write(html.ToString());

w.Close();

}

catch (Exception ex)

{

throw ex;

}

} //Fin de la Función Export

/// <summary>

/// Genera un archivo CSV

/// </summary>

/// <param name="titulos"></param>

/// <param name="datos"></param>

public void ExportCSV(ArrayList titulos, DataTable datos)

{

try

{

FileStream fs = new FileStream(ruta, FileMode.Create,

FileAccess.ReadWrite);

Page 29: Word PDF Excel HTML Con C#

w = new StreamWriter(fs);

string comillas = char.ConvertFromUtf32(34);

StringBuilder CSV = new StringBuilder();

//Encabezados

for (int i = 0; i < titulos.Count; i++)

{

if (i != (titulos.Count - 1))

CSV.Append(comillas + titulos[i].ToString() + comillas + ",");

else

CSV.Append(comillas + titulos[i].ToString() + comillas

+ Environment.NewLine);

}

// se generan datos

for (int i = 0; i < datos.Rows.Count; i++)

{

for (int j = 0; j < datos.Columns.Count; j++)

{

if (j != (titulos.Count - 1))

CSV.Append(comillas + datos.Rows[i][j].ToString()

+ comillas + ",");

else

CSV.Append(comillas + datos.Rows[i][j].ToString()

+ comillas + Environment.NewLine);

}

}

Page 30: Word PDF Excel HTML Con C#

w.Write(CSV.ToString()); //se escribe la cadena en el archivo

w.Close();

}

catch (Exception ex)

{

throw ex;

}

} //Fin de ExportCSV

} // Fin de Clase OtrosFormatos

 

Código del uso de esta clase en la Aplicación para Exportar a Excel.

//Código para exportar a Excel

//Evento Onclick del Botón

private void BotExcel_Click(object sender, EventArgs e)

{

try

{

ArrayList titulos = new ArrayList();

DataTable datosTabla = new DataTable();

//Especificar ruta del archivo con extensión de EXCEL.

OtrosFormatos OF = new OtrosFormatos(Application.StartupPath

+ @\\test.xls);

//obtenemos los titulos del grid y creamos las columnas de la tabla

foreach (DataGridViewColumn item in dataGridView1.Columns)

{

titulos.Add(item.HeaderText);

datosTabla.Columns.Add();

}

Page 31: Word PDF Excel HTML Con C#

//se crean los renglones de la tabla

foreach (DataGridViewRow item in dataGridView1.Rows)

{

DataRow rowx = datosTabla.NewRow();

datosTabla.Rows.Add(rowx);

}

//se pasan los datos del dataGridView a la tabla

foreach (DataGridViewColumn item in dataGridView1.Columns)

{

foreach (DataGridViewRow itemx in dataGridView1.Rows)

{

datosTabla.Rows[itemx.Index][item.Index] =

dataGridView1[item.Index, itemx.Index].Value;

}

}

OF.Export(titulos, datosTabla);

Process.Start(OF.xpath);

MessageBox.Show("Proceso Completo");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

} //Fin del Evento Clic del Botón

 

Page 32: Word PDF Excel HTML Con C#

Archivo de Excel Resultante.

Exportación a WORD

Para la exportación de los datos a Word se sigue el mismo procedimiento que para exportar los datos a Excel, solo que en vez de guardar el archivo con extensión .xls lo guardamos con extensión .doc.

//Código para exportar a Word

//Evento Onclick del Botón

private void BotWord_Click(object sender, EventArgs e)

{

try

{

ArrayList titulos = new ArrayList();

DataTable datosTabla = new DataTable();

//Especificar ruta del archivo con extensión de WORD.

OtrosFormatos OF = new OtrosFormatos(Application.StartupPath

+ @\\test.doc);

//obtenemos los titulos del grid y creamos las columnas de la tabla

foreach (DataGridViewColumn item in dataGridView1.Columns)

{

Page 33: Word PDF Excel HTML Con C#

titulos.Add(item.HeaderText);

datosTabla.Columns.Add();

}

//se crean los renglones de la tabla

foreach (DataGridViewRow item in dataGridView1.Rows)

{

DataRow rowx = datosTabla.NewRow();

datosTabla.Rows.Add(rowx);

}

//se pasan los datos del dataGridView a la tabla

foreach (DataGridViewColumn item in dataGridView1.Columns)

{

foreach (DataGridViewRow itemx in dataGridView1.Rows)

{

datosTabla.Rows[itemx.Index][item.Index] =

dataGridView1[item.Index, itemx.Index].Value;

}

}

OF.Export(titulos, datosTabla);

Process.Start(OF.xpath);

MessageBox.Show("Proceso Completo");

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

} //Fin del Evento Clic del Botón

Page 34: Word PDF Excel HTML Con C#

Archivo .doc Resultante

Exportación a HTML

Para la exportación a HTML es la mas sencilla ya que en este ejemplo lo que se crea es un archivo HTML solo se guarda con extensión HTML y ya esta.

//Código para Exportar a HTML

//Evento Click del Botón

private void BotHTML_Click(object sender, EventArgs e)

{

try

{

ArrayList titulos = new ArrayList();

DataTable datosTabla = new DataTable();

//Especificar ruta del archivo con extensión de HTML.

OtrosFormatos OF = new OtrosFormatos(Application.StartupPath

+ @\\test.html);

//obtenemos los titulos del grid y creamos las columnas de la tabla

foreach (DataGridViewColumn item in dataGridView1.Columns)

{

Page 35: Word PDF Excel HTML Con C#

titulos.Add(item.HeaderText);

datosTabla.Columns.Add();

}

//se crean los renglones de la tabla

foreach (DataGridViewRow item in dataGridView1.Rows)

{

DataRow rowx = datosTabla.NewRow();

datosTabla.Rows.Add(rowx);

}

//se pasan los datos del dataGridView a la tabla

foreach (DataGridViewColumn item in dataGridView1.Columns)

{

foreach (DataGridViewRow itemx in dataGridView1.Rows)

{

datosTabla.Rows[itemx.Index][item.Index] =

dataGridView1[item.Index, itemx.Index].Value;

}

}

OF.Export(titulos, datosTabla);

Process.Start(OF.xpath);

MessageBox.Show("Proceso Completo");

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

} // Fin del Evento Click del botón

Page 36: Word PDF Excel HTML Con C#

Archivo html resultante

 Exportación a CSV (comma-separated values)

La exportación a este formato es bastante sencilla y se usa el mismo principio que en los demás solo que usando el método ExportCSV de este ejemplo ya que el vaciado de los datos es diferente porque no se crea un documento HTML sino que se escribe directamente sobre un archivo csv.

Nota: Cabe señalar que este tipo de formatos se puede abrir también en Excel en cual se mostrara los datos en forma de tabla.

//Código para Exportar a CSV

//Evento Click del Botón

private void BotCSV_Click(object sender, EventArgs e)

{

try

{

ArrayList titulos = new ArrayList();

DataTable datosTabla = new DataTable();

//Especificar ruta del archivo con extensión de CSV.

OtrosFormatos OF = new OtrosFormatos(Application.StartupPath

Page 37: Word PDF Excel HTML Con C#

+ @\\test.csv);

//obtenemos los titulos del grid y creamos las columnas de la tabla

foreach (DataGridViewColumn item in dataGridView1.Columns)

{

titulos.Add(item.HeaderText);

datosTabla.Columns.Add();

}

//se crean los renglones de la tabla

foreach (DataGridViewRow item in dataGridView1.Rows)

{

DataRow rowx = datosTabla.NewRow();

datosTabla.Rows.Add(rowx);

}

//se pasan los datos del dataGridView a la tabla

foreach (DataGridViewColumn item in dataGridView1.Columns)

{

foreach (DataGridViewRow itemx in dataGridView1.Rows)

{

datosTabla.Rows[itemx.Index][item.Index] =

dataGridView1[item.Index, itemx.Index].Value;

}

}

OF.ExportCSV(titulos, datosTabla);

Process.Start(OF.xpath);

MessageBox.Show("Proceso Completo");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

Page 38: Word PDF Excel HTML Con C#

}

} //Fin del Evento Click del Botón

 

Archivo CSV resultante

Este ejemplo en conjunto con todo su código lo pueden descargar desde mi SkyDrive aquí.

Nota: La conexión a la base de datos de este ejemplo la realice con SQLite, en el ejemplo pongo lo necesario para que funcione el ejecutable incluyendo la base de datos, la DLL iTextSharp y el DataProvider de SQLite, pero si quieren modificar el código y que funcione tendrán que instalar el Proveedor de datos SQLite, esto lo hice por portabilidad ya que con SQlite la base de datos esta en un pequeño archivo.

Pueden preguntar con toda confianza por si tiene alguna duda con SQLite y si esta dentro de mis posibilidades intentare ayudarlos.

Saludos!!!

Page 39: Word PDF Excel HTML Con C#