how to export into excel from datagrid in c#

Posted by Rimjhim4 under C# on 4/4/2012 | Points: 10 | Views : 10210 | Status : [Member] | Replies : 3
how to export into excel from datagrid in c#??????????




Responses

Posted by: Savariya on: 4/4/2012 [Member] Starter | Points: 25

Up
0
Down
//you will need this import in your application: System.IO because of the StreamWriter Object

//fxn that exports content of a datagridview object to an excel file

//note: excel_file represents the complete physical address of excel file eg C:/myexcel.xls


public void export_datagridview_to_excel(DataGridView dgv, string excel_file)
{
int cols;
//open file
StreamWriter wr = new StreamWriter(excel_file);

//determine the number of columns and write columns to file
cols = dgv.Columns.Count;
for (int i = 0; i < cols; i++)
{
wr.Write(dgv.ColumnsIdea.Name.ToString().ToUpper() + "\t");
}

wr.WriteLine();

//write rows to excel file
for (int i = 0; i < (dgv.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dgv.RowsIdea.Cells[j].Value != null)
wr.Write(dgv.RowsIdea.Cells[j].Value + "\t");
else
{
wr.Write("\t");
}
}

wr.WriteLine();
}

//close file
wr.Close();
}






Rimjhim4, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ajay.Kalol on: 4/5/2012 [Member] Starter | Points: 25

Up
0
Down
 protected void btnExport_OnClick(object source, RepeaterCommandEventArgs e)

{
grid.AllowPaging = False; // Required because grid is not export when
grid.AllowSorting = False; // paging and sorting is allowed
BindGrid(); // Bind grid again without paging and sorting

Response.Clear() ; // Clear the response
// Set the type and filename
Response.AddHeader("content-disposition", "attachment;filename = GridData.xls") ;
Response.Charset = "";
Response.ContentType = "application/ms-excel"; // Set Response Type

/// Add the HTML from the GridView to a StringWriter so we can write it out later

System.IO.StringWriter sw = New System.IO.StringWriter;
System.Web.UI.HtmlTextWriter hw = New HtmlTextWriter(sw);
grid.RenderControl(hw);

// Write out the data
Response.Write(sw.ToString);
Response.End();
grid.AllowPaging = True; // again set Paging and Sorting and Bing Grid Again
grid.AllowSorting = True;
BindGrid();
}
public override void VerifyRenderingInServerForm(Control control)
{
base.VerifyRenderingInServerForm(control);
}


if your gridview do not have paging or sorting then there is not need to set Paging and Sorting and Grid Binding .

Ajay
ajaypatelfromsanthal.blogspot.in

Rimjhim4, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Prabhakar on: 4/5/2012 [Member] [MVP] Starter | Points: 25

Up
0
Down
Hi Rimjhim..

Go with this DotNetFunda Article .. it's help us u . .


http://www.dotnetfunda.com/articles/article1131-export-large-data-from-gridview-to-excel-file-using-csharp.aspx

Best Regard's
Prabhakar

Rimjhim4, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response