Export data to datagerid
-
hi.i need to export data from datagrid to excel.can you please help me or give me link that i can refer from it
public string Convert(DataTable oDataTable, string directoryPath, string fileName) { string fullpath = ""; if (directoryPath.Substring(directoryPath.Length - 1,1) == @"\" ||directoryPath.Substring(directoryPath.Length - 1,1) == "/") { fullpath = directoryPath + fileName; } else { fullpath = directoryPath + @"\" + fileName; } StreamWriter SW; SW=File.CreateText(fullpath); StringBuilder oStringBuilder = new StringBuilder(); /******************************************************************* * Start, Creating column header * *****************************************************************/ foreach(DataColumn oDataColumn in oDataTable.Columns) { oStringBuilder.Append(oDataColumn.ColumnName + ","); } SW.WriteLine(oStringBuilder.ToString().Substring(0,oStringBuilder.ToString().Length - 1)); oStringBuilder.Length = 0; /******************************************************************* * End, Creating column header * *****************************************************************/ /******************************************************************* * Start, Creating rows * *****************************************************************/ foreach(DataRow oDataRow in oDataTable.Rows) { foreach(DataColumn oDataColumn in oDataTable.Columns) { oStringBuilder.Append(oDataRow[oDataColumn.ColumnName] + ","); } SW.WriteLine(oStringBuilder.ToString().Substring(0,oStringBuilder.ToString().Length - 1)); oStringBuilder.Length = 0; } /******************************************************************* * End, Creating rows * *****************************************************************/ SW.Close(); return fullpath; } write the above code in a class file. and write the below code in your button click event string fileName = System.Guid.NewGuid().ToString().Replace("-","") + ".xls"; (new BLC.CSVConvertor()).Convert(Generatexlsheet() ,Server.MapPath("."),fileName); Response.Redirect(fileName); end of button click event //below is the code for Generatexlsheet : private DataTable Generatexlsheet() { String dbstr = BLC.Class1.Constring(); SqlConnection objconn = new SqlConnection(dbstr); objconn.Open(); // SqlDataReader sqldr = null; // // // SqlCommand cmd = new SqlCommand("select * from employees",objconn