Export data from gridview to csv file
C#
3
Posts
3
Posters
0
Views
1
Watching
-
Does this works?
StreamWriter oWriter = new StreamWriter("CSV File Path", false); // First we will write the headers. for(int i = 0; i < oGridView.Columns.Count; i++) { oWriter.Write(oGridView.Columns[i].HeaderText); if(i < oGridView.Columns.Count - 1) { oWriter.Write(","); } } oWriter.Write(oWriter.NewLine); // Now write all the rows. foreach(DataGridViewRow dr in oGridView.Rows) { for(int i = 0; i < oGridView.Columns.Count; i++) { oWriter.Write(dr.Cells[i].Value.ToString()); if(i < oGridView.Columns.Count - 1) { oWriter.Write(","); } } oWriter.Write(oWriter.NewLine); } oWriter.Close();
modified on Wednesday, May 14, 2008 4:24 AM
-
Hope this will help you :
private void OnExportGridToCSV(object sender, System.EventArgs e) { // Create the CSV file to which grid data will be exported. StreamWriter sw = new StreamWriter(Server.MapPath("~/GridData.txt"), false); // First we will write the headers. DataTable dt = m_dsProducts.Tables[0]; int iColCount = dt.Columns.Count; for(int i = 0; i < iColCount; i++) { sw.Write(dt.Columns[i]); if (i < iColCount - 1) { sw.Write(","); } } sw.Write(sw.NewLine); // Now write all the rows. foreach (DataRow dr in dt.Rows) { for (int i = 0; i < iColCount; i++) { if (!Convert.IsDBNull(dr[i])) { sw.Write(dr[i].ToString()); } if ( i < iColCount - 1) { sw.Write(","); } } sw.Write(sw.NewLine); } sw.Close(); }