Friday, December 30, 2011

export gridview to excel in

Title:How to Export data from grid view to excel in c#

As per previous articles we have gone through some examples like Export grid view data to word document,Export grid view to PDF,Import excel data to Grid view ,Export data to excel in i would like to share  how to export grid view data to Excel sheet in using can be done in two steps.First is render to HTML from grid view then the present HTML to Excel.

<html xmlns="">
<form id="form1" runat="server">
<asp:GridView ID="GdvMainmasters" Runat="server" DataSourceID="OrdrDb">
<asp:BoundField DataField="OrderID" HeaderText="OrderID" 
SortExpression="OrderID" />
<asp:BoundField DataField="OrderName" HeaderText="OrderName" 
SortExpression="OrderName" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:BoundField DataField="Address" HeaderText="Address" 
SortExpression="Address" />
<asp:BoundField DataField="Amount" HeaderText="Amount" 
SortExpression="Amount" />
<asp:SqlDataSource ID="OrdrDb" runat="server" 
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>" 
SelectCommand="SELECT * FROM [Orders]"></asp:SqlDataSource>
<asp:Button ID="btnexportOrderstoWord" runat="server" Text="ExportExcel" 
onclick="btnexportOrderstoWord_Click" /></div>
<asp:Lable id="LblMsg" runat="server"/>
<asp:Button id="BtnSendtoExcel" Text="Export" runat="server" OnClick="BtnSendtoExcel_Click"/>

protected void BtnSendtoExcel_Click(object sender, EventArgs e)
Excelbtn = "ABC";
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
StringWriter swr = new StringWriter();
HtmlTextWriter hwr = new HtmlTextWriter(sw);
GdvMainmasters.AllowPaging = false;
GdvMainmasters.AutoGenerateSelectButton = false;
GdvMainmasters.Enabled = false;
GdvMainmasters.HeaderRow.Cells[0].BorderStyle = BorderStyle.Inset;
GdvMainmasters.HeaderRow.Cells[1].BorderStyle = BorderStyle.Inset;
GdvMainmasters.HeaderRow.Cells[2].BorderStyle = BorderStyle.Inset;
GdvMainmasters.HeaderRow.Cells[3].BorderStyle = BorderStyle.Inset;
GdvMainmasters.HeaderRow.Cells[3].BorderStyle = BorderStyle.Inset;
for (int j = 0; j < GdvMainmasters.Rows.Count; j++)
GridViewRow row = GdvMainmasters.Rows[j];
catch (Exception e3)
LblMsg.Text = e3.Message;

Note:While run the above code we may get the some errors RegisterForEventValidation can only be called during Render.If you get an error then need to override the control.


webmonkeymon said...

Thank you very much sir!
I did get this to work. I typically am working in VB now so had to struggle a bit to fix a few minor issues with syntax. Case sensitive Capital letters! ahh!

all very minor. without to much got it to work.

not sure i understand why their are two buttons?

Big thank you.

webmonkeymon said...

Thank you Sir!!

it was a big help!!

Unknown said...

i have 93 column how to define that field