Click here to Skip to main content
15,905,229 members
Articles / Programming Languages / C#
Tip/Trick

Export GridView Using OPENXML - Part 1

Rate me:
Please Sign up or sign in to vote.
4.29/5 (3 votes)
21 Aug 2015CPOL 10.8K   7   4
How to export the gridview table into document using the OpenXML

In this tip, I am going to show how to export the gridview table into document using the OpenXML.

Download the OPENXML from here.

After downloading the SDK, install the .exe into your PC.

Now, open a new project in your C# tool.

Add the OpenXML SDK Reference in your project. Also include Windowsbase into the reference.

Using the Code

Now use the following namespace in your source code:

C#
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using System.IO.Packaging;

After including the above namespace, design your table using the XML file. Mine looks like below:

Add the data to the Datagridview.

Now it’s time for us to create document Template using the below code:

C#
//count number of column available in Gridview

int columncount=dataGridView1.Columns.Count;
    
using (WordprocessingDocument wpc=WordprocessingDocument.Create
	(filename,WordprocessingDocumentType.Document))
    
    {                
    // Add a new main document part. 
   MainDocumentPart mainPart = wpc.AddMainDocumentPart(); 
   
    //Create DOM tree for simple document. 
   mainPart.Document = new Document();
   
    // Save changes to the main document part.
   Body body = new Body(); 
           Table table = new Table();

        // Create a TableProperties object and specify its border information.
        TableProperties tblProp = new TableProperties(
            new TableBorders(
                new TopBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicBlackDots), Size = 20 },
                new BottomBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicBlackDots), Size = 20 },
                new LeftBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicBlackDots), Size = 20 },
                new RightBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicBlackDots), Size = 20 },
                new InsideHorizontalBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicBlackDots), Size = 20 },
                new InsideVerticalBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicBlackDots), Size = 20 }
            )
        );

        // Append the TableProperties object to the empty table.
        table.AppendChild<TableProperties>(tblProp);

        // Create a row.
        
        TableRow tr = new TableRow();
        
        //create Dynamic object by using array.
        
        TableCell[] tc1 = new TableCell[5];

        // this loop allow us to create multiple column according to the Gridview

        for(int i=0;i<columncount;i++)
        {
        string[] columnhead=new string[columncount];
        columnhead[i]=dataGridView1.Columns[i].HeaderText.ToString();
        
        // Create a cell.
        tc1[i]=new TableCell();

        // Specify the width property of the table cell.
        tc1[i].Append(new TableCellProperties(
            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

        // Specify the table cell content.
        tc1[i].Append(new Paragraph
        (new Run(new Text(columnhead[i]))));

        // Append the table cell to the table row.
        tr.Append(tc1[i]);
   
        }
        // Append the table row to the table.
        table.Append(tr);
   body.Append(table);
   mainPart.Document.Append(body);
   mainPart.Document.Save(); 

Then open the document and then pass the data in the Gridview by using the below code:

C#
int rowcount=dataGridView1.Rows.Count;
    int columncount=dataGridView1.Columns.Count;
        
    {
        using (WordprocessingDocument doc = WordprocessingDocument.Open(filename, true))
    {
        // Create an empty table.
        Table table = new Table();

        // Create a TableProperties object and specify its border information.
        TableProperties tblProp = new TableProperties(
            new TableBorders(
                new TopBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicThinLines), Size = 20 },
                new BottomBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicThinLines), Size = 20 },
                new LeftBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicThinLines), Size = 20 },
                new RightBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicThinLines), Size = 20 },
                new InsideHorizontalBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicThinLines), Size = 20 },
                new InsideVerticalBorder() { Val = 
                    new EnumValue<BorderValues>(BorderValues.BasicThinLines), Size = 20 }
            )
        );

        // Append the TableProperties object to the empty table.
        table.AppendChild<TableProperties>(tblProp);
   
for (int i = 0; i < rowcount; i++) 
{
       // Create a row.
      TableRow tr = new TableRow();

        // Create a cell.
        TableCell[] tc1 = new TableCell[columncount];
        
    for (int j = 0; j < columncount; j++) 
    {
        tc1[j]=new TableCell();
        string data1=dataGridView1.Rows[i].Cells[j].Value.ToString();
                
          // Specify the width property of the table cell.
          tc1[j].Append(new TableCellProperties(
            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
                  // Specify the table cell content.
                  tc1[j].Append(new Paragraph
                  (new Run(new Text(data1))));
        tr.Append(tc1[j]);        
    }
    // Append the table row to the table.
     table.Append(tr);
}

        // Append the table to the document.
        doc.MainDocumentPart.Document.Body.Append(table);
        doc.Close();    
        }
    }    

Design the table according to your wish.

And have fun by using the OpenXML.

Happy coding!!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionDo you have a Word version? Pin
cas20007-Sep-15 2:39
cas20007-Sep-15 2:39 
Hi,

I haven't found any documentation on how to add an image inside a cell on a table on a Word document.

Any help would be greatly appreciated.
AnswerRe: Do you have a Word version? Pin
Mohammed Ibrahim.L7-Sep-15 11:48
professionalMohammed Ibrahim.L7-Sep-15 11:48 
GeneralGood Article Pin
aarif moh shaikh21-Aug-15 18:16
professionalaarif moh shaikh21-Aug-15 18:16 
GeneralRe: Good Article Pin
Mohammed Ibrahim.L21-Aug-15 21:29
professionalMohammed Ibrahim.L21-Aug-15 21:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.