Tuesday, May 11, 2010

Export DataGRID SQL Table to CSV file C#


This snippet shows how to export to a Comma Separated File delimited by a comma:


public void ExportGridToExcel(GridView gv, string fileName1)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName1));
Response.Charset = "";
Response.ContentType = "application/vnd.csv";
System.IO.StringWriter sWriter;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sWriter = new System.IO.StringWriter(sb);
string Str;
for (int k = 0; k <= (gv.Columns.Count - 1); k++) { sWriter.Write(gv.HeaderRow.Cells[k].Text + ","); } sWriter.WriteLine(","); for (int i = 0; i <= (gv.Rows.Count - 1); i++) { for (int j = 0; j <= (gv.Columns.Count - 1); j++) { Str = (gv.Rows[i].Cells[j].Text.ToString().Replace("
", ""));
if (Str == " ")
{
Str = "";
}

//Put quotation marks on either side of text
//so that commas in text are not treated as delimiters
Str = "\"" + Str + "\"" + ",";
sWriter.Write(Str);
}
sWriter.WriteLine();
}
sWriter.Close();
Response.Write(sb.ToString());
Response.End();


}
protected void Button2_Click1(object sender, EventArgs e)
{
ExportGridToExcel(GridView1, "Software_Export");
}

No comments:

Post a Comment

Generating "Always On Top" NSWindow in macOS across all detected displays

Also: Using UIKit & Cocoa Frameworks using Objective-C In m acOS or OS X , written in either Objective-C or Swift  Langues, you m...