Set PageSize while Exporting ASP.Net GridView to Word document using C# and VB.Net

Last Reply 6 months ago By dharmendr

Posted 6 months ago

Hello Sir,

I am trying to export the gridview content to word, so here how to set the page size for A4 while export and also how to make the gridview display at the center in word. 

Thanks

You are viewing reply posted by: dharmendr 6 months ago.
Posted 6 months ago Modified on 6 months ago

Hi democloud,

Check this example. Now please take its reference and correct your code.

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data;
using Word = Microsoft.Office.Interop.Word;

VB.Net

Imports System.Data
Imports Word = Microsoft.Office.Interop.Word

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        BindGrid();
        Export_Data_To_Word(GridView1, @"C:\Test.doc");
    }
}
private void BindGrid()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
    dt.Rows.Add(1, "John Hammond", "United States");
    dt.Rows.Add(2, "Mudassar Khan", "India");
    dt.Rows.Add(3, "Suzanne Mathews", "France");
    dt.Rows.Add(4, "Robert Schidner", "Russia");
    GridView1.DataSource = dt;
    GridView1.DataBind();
}
public void Export_Data_To_Word(GridView gridView, string filename)
{
    if (gridView.Rows.Count != 0)
    {
        int RowCount = gridView.Rows.Count;
        int ColumnCount = gridView.Columns.Count;
        Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

        //Adding Rows.
        int r = 0;
        for (int c = 0; c <= ColumnCount - 1; c++)
        {
            for (r = 0; r <= RowCount - 1; r++)
            {
                DataArray[r, c] = gridView.Rows[r].Cells[c].Text;
            }
        }

        Word.Document oDoc = new Word.Document();
        oDoc.Application.Visible = true;

        //Page Orientation.
        oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
        //Page PaperSize.
        oDoc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4;


        dynamic oRange = oDoc.Content.Application.Selection.Range;
        string oTemp = "";
        for (r = 0; r <= RowCount - 1; r++)
        {
            for (int c = 0; c <= ColumnCount - 1; c++)
            {
                oTemp = oTemp + DataArray[r, c] + "\t";

            }
        }

        //Table Format
        oRange.Text = oTemp;

        object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;
        object ApplyBorders = true;
        object AutoFit = true;
        object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;

        oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
                                Type.Missing, Type.Missing, ref ApplyBorders,
                                Type.Missing, Type.Missing, Type.Missing,
                                Type.Missing, Type.Missing, Type.Missing,
                                Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);

        oRange.Select();

        oDoc.Application.Selection.Tables[1].Select();
        oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
        oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
        oDoc.Application.Selection.Tables[1].Rows[1].Select();
        oDoc.Application.Selection.InsertRowsAbove(1);
        oDoc.Application.Selection.Tables[1].Rows[1].Select();

        //header row style
        oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
        oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma";
        oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

        //Add header row manually.
        for (int c = 0; c <= ColumnCount - 1; c++)
        {
            oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = gridView.Columns[c].HeaderText;
        }

        //header text
        foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)
        {
            Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
            headerRange.Text = "your header text";
            headerRange.Font.Size = 16;
            headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
        }

        //save the file
        oDoc.SaveAs(filename);
        oDoc.Application.Quit();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        BindGrid()
        Export_Data_To_Word(GridView1, "C:\Test.doc")
    End If
End Sub

Private Sub BindGrid()
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
    dt.Rows.Add(1, "John Hammond", "United States")
    dt.Rows.Add(2, "Mudassar Khan", "India")
    dt.Rows.Add(3, "Suzanne Mathews", "France")
    dt.Rows.Add(4, "Robert Schidner", "Russia")
    GridView1.DataSource = dt
    GridView1.DataBind()
End Sub

Public Sub Export_Data_To_Word(ByVal gridView As GridView, ByVal filename As String)
    If gridView.Rows.Count <> 0 Then
        Dim RowCount As Integer = gridView.Rows.Count
        Dim ColumnCount As Integer = gridView.Columns.Count
        Dim DataArray As Object(,) = New Object(RowCount + 1 - 1, ColumnCount + 1 - 1) {}
        Dim r As Integer = 0

        For c As Integer = 0 To ColumnCount - 1

            For r = 0 To RowCount - 1
                DataArray(r, c) = gridView.Rows(r).Cells(c).Text
            Next
        Next

        Dim oDoc As Word.Document = New Word.Document()
        oDoc.Application.Visible = True
        oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape
        oDoc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4
        Dim oRange As Object = oDoc.Content.Application.Selection.Range
        Dim oTemp As String = ""

        For r = 0 To RowCount - 1

            For c As Integer = 0 To ColumnCount - 1
                oTemp = oTemp & DataArray(r, c) & vbTab
            Next
        Next

        oRange.Text = oTemp
        Dim Separator As Object = Word.WdTableFieldSeparator.wdSeparateByTabs
        Dim ApplyBorders As Object = True
        Dim AutoFit As Object = True
        Dim AutoFitBehavior As Object = Word.WdAutoFitBehavior.wdAutoFitContent
        oRange.ConvertToTable(Separator, RowCount, ColumnCount, Type.Missing, Type.Missing, ApplyBorders, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, AutoFit, AutoFitBehavior, Type.Missing)
        oRange.[Select]()
        oDoc.Application.Selection.Tables(1).[Select]()
        oDoc.Application.Selection.Tables(1).Rows.AllowBreakAcrossPages = 0
        oDoc.Application.Selection.Tables(1).Rows.Alignment = 0
        oDoc.Application.Selection.Tables(1).Rows(1).[Select]()
        oDoc.Application.Selection.InsertRowsAbove(1)
        oDoc.Application.Selection.Tables(1).Rows(1).[Select]()
        oDoc.Application.Selection.Tables(1).Rows(1).Range.Bold = 1
        oDoc.Application.Selection.Tables(1).Rows(1).Range.Font.Name = "Tahoma"
        oDoc.Application.Selection.Tables(1).Rows(1).Range.Font.Size = 14

        For c As Integer = 0 To ColumnCount - 1
            oDoc.Application.Selection.Tables(1).Cell(1, c + 1).Range.Text = gridView.Columns(c).HeaderText
        Next

        For Each section As Word.Section In oDoc.Application.ActiveDocument.Sections
            Dim headerRange As Word.Range = section.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
            headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage)
            headerRange.Text = "your header text"
            headerRange.Font.Size = 16
            headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
        Next

        oDoc.SaveAs(filename)
        oDoc.Application.Quit()
    End If
End Sub

Screenshot