Export GridView with Images from database to different file formats in asp.net

Description:-

In this article I am explaining how to Export GridView to different file format which has images and pictures in it.  Here I am exporting a GridView which is displaying images stored on disk and the respective paths stored in SQL Server Database.

Using Gridview control we can export it in different file format like word, excel, pdf etc.. here I have done with all to export Gridview control with images or data to export file. 

Here i have given a sample example to export in different file format.

Create table:-
CREATE TABLE [dbo].[Image_Mst](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [ImageFile] [nvarchar](max) NOT NULL,
 [ImageFilePath] [nvarchar](max) NOT NULL,
 CONSTRAINT [PK_Image_Mst] PRIMARY KEY CLUSTERED 
(
 [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Default.aspx:-
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Font-Names="Arial">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" />
                <asp:BoundField DataField="ImageFile" HeaderText="Image Name" />
                <asp:TemplateField HeaderText="Image Preview">
                    <ItemTemplate>
                        <asp:Image ID="Image1" Height="80px" Width="100px" runat="server" ImageUrl='<%# Eval("ImageFilePath", GetUrl("{0}"))%>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    <br />
    <asp:Button ID="btnExportWord" CommandArgument="Word" runat="server" Text="Export Word" OnClick="Export_Grid" />
    <asp:Button ID="btnExportExcel" CommandArgument="Excel" runat="server" Text="Export Excel" OnClick="Export_Grid" />
    <asp:Button ID="btnExportPDF" CommandArgument="PDF" runat="server" Text="Export PDF" OnClick="Export_Grid" />

Web.config:-
<connectionStrings>
    <add connectionString="ConnectionString" name="DBCS" providerName="System.Data.SqlClient"/>   
</connectionStrings>

Default.aspx.cs:-
protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    string strQuery = "select * from Image_Mst order by ID";
    SqlCommand cmd = new SqlCommand(strQuery);
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
        dt.Dispose();
    }
}

protected string GetUrl(string page)
{
    string[] splits = Request.Url.AbsoluteUri.Split('/');
    if (splits.Length >= 2)
    {
        string url = splits[0] + "//";
        for (int i = 2; i < splits.Length - 1; i++)
        {
            url += splits[i];
            url += "/";
        }
        return url + page;
    }
    return page;
}

protected void Export_Grid(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    switch (btn.CommandArgument)
    {
        case "Word":
            Word_Export();
            break;
        case "Excel":
            Excel_Export();
            break;
        case "PDF":
            PDF_Export();
            break;
    }
}

private void Word_Export()
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition","attachment;filename=GridViewExport.doc");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-word ";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

private void Excel_Export()
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        GridViewRow row = GridView1.Rows[i];
        //Apply text style to each Row
        row.Attributes.Add("class", "textmode");
    }
    GridView1.RenderControl(hw);
    //style to format numbers to string
    string style = @"<style> .textmode { mso-number-format:\@; } </style>";
    Response.Write(style);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

private void PDF_Export()
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition","attachment;filename=GridViewExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

Related Posts

Previous
Next Post »

Thanks for comments.....