In this article I will explain with an example, how to export GridView with Images from Folder (Directory) to Word, Excel and PDF formats in ASP.Net using C# and VB.Net.
Exporting GridView to Word and Excel can be easily achieved using ASP.Net without any third party tools, but for exporting to PDF iTextSharp library will be used.
This article will illustrate how to export GridView with Images to Word, Excel and PDF file along with formatting i.e. Styles and Colors in ASP.Net.
 
 
Folder Structure
The following screenshot describes the Folder Structure of the Images folder in the project.
Export GridView with Images to Word Excel and PDF Formats in ASP.Net
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net GridView control with one BoundField column, one ImageField column and three Button controls.
The Buttons have been assigned OnClick event handlers which will perform the operation for exporting GridView to Word, Excel and PDF files.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    Font-Names="Arial" Font-Size="10" RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White"
    AlternatingRowStyle-ForeColor="#000" runat="server" AutoGenerateColumns="false">
    <Columns>
       <asp:BoundField DataField="Text" HeaderText="File Name"/>
       <asp:ImageField DataImageUrlField="Value" ItemStyle-Height="150" ItemStyle-Width="100"/>
    </Columns>
</asp:GridView>
<br/>
<asp:Button ID="btnExcel" runat="server" Text="Export To Excel" OnClick="ExportToExcel" Width="120"/>
<asp:Button ID="btnWord" runat="server" Text="Export To Word" OnClick="ExportToWord" Width="120"/>
<asp:Button ID="btnPDF" runat="server" Text="Export To PDF" OnClick="ExportToPDF" Width="120"/>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Drawing;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
 
VB.Net
Imports System.IO
Imports System.Drawing
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
 
 
Binding the GridView
In the Page Load event, the URL to the Images folder is built by concatenation of the URL segments.
Then the Images are fetched from the Folder (Directory) using the GetFiles function of the Directory class and a loop is executed over the fetched Image files.
Inside the loop, the Image Path is converted into an Absolute Path and then set into a Generic collection of ListItem class.
Note: In order to export to Word, Excel or PDF, it is important to generate the complete URL of the Image file like this http://localhost:1045/Export_GridView_Images_ASP.Net/Images/Desert.jpg.
Such URLs are known as Absolute Path and Word, Excel and PDF files will use this path to download the Image files within the application.
 
Finally, the Generic collection of ListItem class is used to populate (bind) the GridView.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    //Fetch the Current URL.
    Uri uri = Request.Url;
 
    //Generate Absolute Path for the Images folder.
    string folderUrl = string.Format("{0}://{1}{2}", uri.Scheme, uri.Authority, uri.AbsolutePath);
    folderUrl = folderUrl.Replace(Request.Url.Segments[Request.Url.Segments.Length - 1], "");
    folderUrl += "Images/";
 
    //Fetch the Images from Images Folder and generate Absolute Path.
    string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
    List<System.Web.UI.WebControls.ListItem> files = new List<System.Web.UI.WebControls.ListItem>();
    foreach (string filePath in filePaths)
    {
        string fileName = Path.GetFileName(filePath);
        files.Add(new System.Web.UI.WebControls.ListItem(fileName, string.Concat(folderUrl, fileName)));
    }
 
    //Bind the GridView.
    GridView1.DataSource = files;
    GridView1.DataBind();
}
 
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Private Sub BindGrid()
    'Fetch the Current URL.
    Dim uri As Uri = Request.Url
 
    'Generate Absolute Path for the Images folder.
    Dim folderUrl As String = String.Format("{0}://{1}{2}", uri.Scheme, uri.Authority, uri.AbsolutePath)
    folderUrl = folderUrl.Replace(Request.Url.Segments(Request.Url.Segments.Length - 1), "")
    folderUrl += "Images/"
 
    'Fetch the Images from Images Folder and generate Absolute Path.
    Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/Images/"))
    Dim files As List(Of System.Web.UI.WebControls.ListItem) = New List(Of System.Web.UI.WebControls.ListItem)()
    For Each filePath As String In filePaths
        Dim fileName As String = Path.GetFileName(filePath)
        files.Add(New System.Web.UI.WebControls.ListItem(fileName, String.Concat(folderUrl, fileName)))
    Next
 
    'Bind the GridView.
    GridView1.DataSource = files
    GridView1.DataBind()
End Sub
 
 
Exporting GridView with Images to Excel with Formatting
When the Export Button is clicked, first the Content Type is set in the Response Stream in order to specify the Browser that the downloading file is an Excel file.
The Paging is disabled for the GridView by setting the AllowPaging property to False and the GridView is again populated with records from the Database by making call to the BindGrid method.
Then a loop is executed over the GridView rows and the style and formatting are applied to the Row and Alternating Row of the GridView control.
Note: The colors are applied to individual cell of each Row and not to the whole Row as if this is not done then the color will spread on all cells of the Excel sheet.
 
CSS class named textmode is applied to each cell of the GridView. This class makes sure that all the contents are rendered in Text format (mso number format).
Note: The mso number format style prevents large numbers from getting converted to exponential values.
 
C#
protected void ExportToExcel(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition""attachment;filename=GridViewExport.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    using (StringWriter sw = new StringWriter())
    {
        HtmlTextWriter hw = new HtmlTextWriter(sw);
 
        //To Export all pages.
        GridView1.AllowPaging = false;
        this.BindGrid();
 
        GridView1.HeaderRow.BackColor = Color.White;
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            cell.BackColor = GridView1.HeaderStyle.BackColor;
        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            row.BackColor = Color.White;
            foreach (TableCell cell in row.Cells)
            {
                if (row.RowIndex % 2 == 0)
                {
                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                }
                else
                {
                    cell.BackColor = GridView1.RowStyle.BackColor;
                }
                cell.CssClass = "textmode";
            }
        }
 
        GridView1.RenderControl(hw);
 
        //Style to format numbers to string.
        string style = @"<style> .textmode { } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
}
 
VB.Net
Protected Sub ExportToExcel(sender As Object, e As EventArgs)
    Response.Clear()
    Response.Buffer = True
    Response.AddHeader("content-disposition""attachment;filename=GridViewExport.xls")
    Response.Charset = ""
    Response.ContentType = "application/vnd.ms-excel"
    Using sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
 
        'To Export all pages.
        GridView1.AllowPaging = False
        Me.BindGrid()
 
        GridView1.HeaderRow.BackColor = Color.White
        For Each cell As TableCell In GridView1.HeaderRow.Cells
            cell.BackColor = GridView1.HeaderStyle.BackColor
        Next
        For Each row As GridViewRow In GridView1.Rows
            row.BackColor = Color.White
            For Each cell As TableCell In row.Cells
                If row.RowIndex Mod 2 = 0 Then
                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor
                Else
                    cell.BackColor = GridView1.RowStyle.BackColor
                End If
                cell.CssClass = "textmode"
            Next
        Next
 
        GridView1.RenderControl(hw)
 
        'Style to format numbers to string.
        Dim style As String = "<style> .textmode { } </style>
        Response.Write(style)
        Response.Output.Write(sw.ToString())
        Response.Flush()
        Response.End()
    End Using
End Sub
 
 
Exporting GridView with Images to Word document with Formatting
When the Export Button is clicked, first the Content Type is set in the Response Stream in order to specify the Browser that the downloading file is a Word document.
The Paging is disabled for the GridView by setting the AllowPaging property to False and the GridView is again populated with records from the Database by making call to the BindGrid method.
Then a loop is executed over the GridView rows and the style and formatting are applied to the Row and Alternating Row of the GridView control.
Finally, GridView is rendered as Word document and written to the Response which initiates the File download.
C#
protected void ExportToWord(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition""attachment;filename=GridViewExport.doc");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-word";
    using (StringWriter sw = new StringWriter())
    {
        HtmlTextWriter hw = new HtmlTextWriter(sw);
 
        //To Export all pages.
        GridView1.AllowPaging = false;
        this.BindGrid();
 
        GridView1.HeaderRow.BackColor = Color.White;
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            cell.BackColor = GridView1.HeaderStyle.BackColor;
        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            row.BackColor = Color.White;
            foreach (TableCell cell in row.Cells)
            {
                if (row.RowIndex % 2 == 0)
                {
                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                }
                else
                {
                    cell.BackColor = GridView1.RowStyle.BackColor;
                }
            }
        }
 
        GridView1.RenderControl(hw);
 
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
}
 
VB.Net
Protected Sub ExportToWord(ByVal sender As ObjectByVal e As EventArgs)
    Response.Clear()
    Response.Buffer = True
    Response.AddHeader("content-disposition""attachment;filename=GridViewExport.doc")
    Response.Charset = ""
    Response.ContentType = "application/vnd.ms-word"
 
    Using sw As StringWriter = New StringWriter()
        Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
 
        'To Export all pages.
        GridView1.AllowPaging = False
        Me.BindGrid()
 
        GridView1.HeaderRow.BackColor = Color.White
        For Each cell As TableCell In GridView1.HeaderRow.Cells
            cell.BackColor = GridView1.HeaderStyle.BackColor
        Next
        For Each row As GridViewRow In GridView1.Rows
            row.BackColor = Color.White 
            For Each cell As TableCell In row.Cells 
                If row.RowIndex Mod 2 = 0 Then
                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor
                Else
                    cell.BackColor = GridView1.RowStyle.BackColor
                End If
            Next
        Next
 
        GridView1.RenderControl(hw)
 
        Response.Output.Write(sw.ToString())
        Response.Flush()
        Response.End()
    End Using
End Sub
 
 
Exporting GridView with Images to PDF with Formatting
Note: The iTextSharp and XmlWorkerHelper DLL files are available in the attached sample of this article.
 
When the Export Button is clicked, first the Content Type is set in the Response Stream in order to specify the Browser that the downloading file is a PDF file.
The Paging is disabled for the GridView by setting the AllowPaging property to False and the GridView is again populated with records from the Database by making call to the BindGrid method.
First, the GridView is rendered into an HTML string using HtmlTextWriter and then the generated HTML is added to the iTextSharp PDF Document, which is then export to PDF through the Response Stream.
C#
protected void ExportToPDF(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition""attachment;filename=GridViewExport.pdf");
    Response.Charset = "";
    Response.ContentType = "application/pdf";
 
    //To Export all pages.
    GridView1.AllowPaging = false;
    this.BindGrid();
 
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            GridView1.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
            pdfDoc.Close();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();
        }
    }
}
 
VB.Net
Protected Sub ExportToPDF(ByVal sender As ObjectByVal e As EventArgs)
    Response.Clear()
    Response.Buffer = True
    Response.AddHeader("content-disposition""attachment;filename=GridViewExport.pdf")
    Response.Charset = ""
    Response.ContentType = "application/pdf"
 
    'To Export all pages.
    GridView1.AllowPaging = False
    Me.BindGrid()
 
    Using sw As StringWriter = New StringWriter()
        Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
            GridView1.RenderControl(hw)
            Dim sr As StringReader = New StringReader(sw.ToString())
            Dim pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
            Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
            pdfDoc.Open()
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr)
            pdfDoc.Close()
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.Write(pdfDoc)
            Response.End()
        End Using
    End Using
End Sub
 
 
Error
When you run the application first time and click on export you might receive the following error.
Server Error in '/ASP.Net' Application.
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
 
The solution to the above exception is to override VerifyRenderingInServerForm event handler, thus informing the Compiler that the control has been rendered explicitly.
C#
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered. */
}
 
VB.Net
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
    ' Verifies that the control is rendered.
End Sub
 
 
Screenshots
GridView
Export GridView with Images to Word Excel and PDF Formats in ASP.Net
 
Exported Excel file
Export GridView with Images to Word Excel and PDF Formats in ASP.Net
 
Exported Word Document
Export GridView with Images to Word Excel and PDF Formats in ASP.Net
 
Exported PDF file
Export GridView with Images to Word Excel and PDF Formats in ASP.Net
 
 
Downloads