I want to export gridview to CSV file using C#, but I get some html code in my exported file. I don't know why this is happening. My someone help me please. I think that my error provide from Response.
Here is my code:
protected void ExportCSV(){
var now = DateTime.Now;
string fileName = Page.ResolveClientUrl("~/downloads/" + now.Day + "_" + now.Month + "_" + now.Year + '-' + now.Hour + "_" + now.Minute + "_" + now.Second + ".csv");
string fullName = HttpContext.Current.Server.MapPath(fileName);
GV1.AllowPaging = false;
StringBuilder sb = new StringBuilder();
DataTable dt = new DataTable();
int colCount = GV1.Columns.Count - 1;
for (int i = 0; i < colCount; i++)
{
dt.Columns.Add(GV1.Columns[i].ToString());
}
foreach (GridViewRow row in GV1.Rows)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < colCount; j++)
{
if (!row.Cells[j].Text.Equals(" "))
{
if(j==0)
dr[GV1.Columns[j].ToString()] = (row.Cells[0].FindControl("lknbtnRowSelected") as LinkButton).Text;
else
dr[GV1.Columns[j].ToString()] = row.Cells[j].Text;
}
}
dt.Rows.Add(dr);
}
foreach (DataColumn col in dt.Columns)
{
sb.Append(col.ColumnName + ';');
}
sb.Remove(sb.Length - 1, 1);
sb.Append(Environment.NewLine);
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sb.Append(row[i].ToString() + ";");
}
sb.Append(Environment.NewLine);
}
sb.ToString().Normalize();
using (StreamWriter writer = new StreamWriter(fullName, true, Encoding.GetEncoding("iso-8859-1")))
{
writer.WriteLine(sb.ToString());
FileInfo info = new FileInfo(fullName);
}
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=" + "file" + now.Day + "_" + now.Month + "_" + now.Year + '-' + now.Hour + "_" + now.Minute + "_" + now.Second + ".csv");
Response.WriteFile(fullName);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch(Exception ex) { }
}