Skip to main content

How To Export gridview data to Excel/PDF , CSV Formates in asp.net C#


Introduction:

Here I will explain how to export Gridview to Word or Excel ,PDF ,CSV Formats using asp.net in c#.


Description:
I have one gridview that has filled with user details now I need to export gridview data to word or excel document based on selection. To implement this functionality first we need to design aspx page like this 


<%@ Page Language="C#" AspCompat="true" AutoEventWireup="true" CodeFile="TestWebPage.aspx.cs"
ValidateRequest="false" Inherits="TestWebPage" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
Font-Size="11pt" AllowPaging="True" OnPageIndexChanging="OnPaging" CellPadding="4"
ForeColor="#333333" GridLines="None">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="UserID" HeaderText="User ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="UserName" HeaderText="User Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
<asp:BoundField ItemStyle-Width="150px" DataField="Address" HeaderText="Address" />
Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White">HeaderStyle>
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White">AlternatingRowStyle>
asp:GridView>
<br />
<asp:Button ID="btnExportWord" runat="server" Text="ExportToWord" OnClick="btnExportWord_Click"/>

<asp:Button ID="btnExportExcel" runat="server" Text="ExportToExcel"OnClick="btnExportExcel_Click" />

<asp:Button ID="btnExportPDF" runat="server" Text="ExportToPDF" OnClick="btnExportPDF_Click" />

<asp:Button ID="Button1" runat="server" Text="ExportToCSV" OnClick="btnExportCSV_Click" />
div>
form>
body>
html>


Code behind Page

Here I will explain how to solve the problem Control 'gvdetails' of type 'GridView' must be placed inside a form tag with runat=server during export of gridview to excel or word or csv using asp.net.
To solve this problem I have added one overriding function VerifyRenderingInServerForm event in code behind it solves my problem.

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

protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}

protected void btnExportWord_Click(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 ";
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();
}
//Excel Foramat
protected void btnExportExcel_Click(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";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

GridView1.AllowPaging = false;
GridView1.DataBind();

//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");

//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "#507CD1");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "#507CD1");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "#507CD1");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "#507CD1");

for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];

//Change Color back to white
row.BackColor = System.Drawing.Color.White;

//Apply text style to each Row
row.Attributes.Add("class", "textmode");

//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#EFF3FB");
row.Cells[1].Style.Add("background-color", "#EFF3FB");
row.Cells[2].Style.Add("background-color", "#EFF3FB");
row.Cells[3].Style.Add("background-color", "#EFF3FB");
}
}
GridView1.RenderControl(hw);

//style to format numbers to string
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
//PDF Format
protected void btnExportPDF_Click(object sender, EventArgs e)
{
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();
}
//CSV format
protected void btnExportCSV_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";

GridView1.AllowPaging = false;
GridView1.DataBind();

StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}

Comments

Popular posts from this blog

Asp.Net AjaxFileUpload Control With Drag Drop And Progress Bar

This Example explains how to use AjaxFileUpload Control With Drag Drop And Progress Bar Functionality In Asp.Net 2.0 3.5 4.0 C# And VB.NET. Previous Post  I was Explained about the   jQuery - Allow Alphanumeric (Alphabets & Numbers) Characters in Textbox using JavaScript  ,  Fileupload show selected file in label when file selected  ,  Check for file size with JavaScript before uploading  . May 2012 release of AjaxControlToolkit includes a new AjaxFileUpload Control  which supports Multiple File Upload, Progress Bar and Drag And Drop functionality. These new features are supported by Google Chrome version 16+, Firefox 8+ , Safari 5+ and Internet explorer 10 + , IE9 or earlier does not support this feature. To start with it, download and put latest AjaxControlToolkit.dll in Bin folder of application, Place ToolkitScriptManager  and AjaxFileUpload on the page. HTML SOURCE < asp:ToolkitScriptManager I...

View online files using the Google Docs Viewer

Use Google Docs Viewer for Document viewing within Browser I was looking for a way to let users see Microsoft Word Doc or PDF files online while using my application without leaving their browser without downloading files and then opening it to view with Word or PDF viewer . I was looking for some way out either via any PHP or Microsoft.NET libraries, did some googling on that; but later on I just got an idea that google already has all code written for me.. when I have any email attachment in PDF or DOC or DOCX google does it for me ..! Even while searching I can see PDFs by converting them in HTML. So I just googled it up and found that Google already has this ability that we can use Google Docs Viewer without any Google Account Login . YES that's true no Google Account login is required. It's damn simple and easy. Just pass document path as attachment as parameter and we are done. Google Docs Viewer gives us ability to embed PDF, DOC/DOCX, PPT, TIFF:...

How to send mail asynchronously in asp.net with MailMessage

With Microsoft.NET Framework 2.0 everything is asynchronous and we can send mail also asynchronously. This features is very useful when you send lots of bulk mails like offers , Discounts , Greetings . You don’t have to wait for response from mail server and you can do other task . By using     SmtpClient . SendAsync Method (MailMessage, Object)    you need to do  System.Net.Mail has also added asynchronous support for sending email. To send asynchronously, you need need to Wire up a SendCompleted event Create the SendCompleted event Call SmtpClient.SendAsync smtpClient.send() will initiate the sending on the main/ui  thread and would block.  smtpClient.SendAsync() will pick a thread from the .NET Thread Pool and execute the method on that thread. So your main UI will not hang or block . Let's create a simple example to send mail. For sending mail asynchronously you need to create a event handler that will notify that mail success...