Hello
I am using Visual Web Developer 2010 Express (with C# as code-behind) to develop a website.
On one of the pages the user can create a report of the data and I would like the user to be able to download the data as a .csv file.
I have written the method to download the data, but the HTML of the page is appended to the data in the downloaded file.
When searching for solutions people say the Response.Clear() and Response.End() must be used in the code, but I have that and it still appends the HTML.
The download method is:
public void ExportCSV(DataTable data, string fileName)
{
try
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
for (int i = 0; i < data.Columns.Count - 1; i++)
{
if (i > 0)
{
context.Response.Write(",");
}
context.Response.Write(data.Columns[i].ColumnName);
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in data.Rows)
{
for (int i = 0; i < data.Columns.Count - 1; i++)
{
if (i > 0)
{
context.Response.Write(",");
}
context.Response.Write(row[i]);
}
context.Response.Write(Environment.NewLine);
}
context.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
Here is part of the file that is downloaded:
HospNumber,LastName,FirstName,DOB,Gender,RaceName,DateDied,AgeAtDeath,HospShort,RTID,
RTNum,RegistrationDate,AgeAtRegDate,OSurvival,Last seen,Next appt,Firm,Clinic,Organ,Part,Histology,Intent,Modality,StGp1,StGp2,T,N,M,Study - Other
90000000,Temp,,18/04/1955 12:00:00 AM,,,,,GSH,61227,2010.1103,14/01/2010 12:00:00 AM,,-1,,,,,,,,,,,,,,,
90001245,TestWeb,,23/02/1983 12:00:00 AM,,,23/06/2011 12:00:00 AM,028,04,00,GSH,,,,,,,,,,,,,,,,,,,,
90003214,TestWeb,,18/01/1983 12:00:00 AM,,,,,GEO,,,,,,,,,,,,,,,,,,,,
900223341,TestWeb,,23/03/1983 12:00:00 AM,,,,,GEO,,,,,,,,,,,,,,,,,,,,
90023541,TestWeb,,23/02/1983 12:00:00 AM,,,,,GEO,,,,,,,,,,,,,,,,,,,,
<script type="text/javascript" language="javascript">alert('Thread was being aborted.');</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title><link href="../Styles/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form method="post" action="../Error.aspx" id="Form2">
Any help will be greatly appreciated. Thank you.
Kobus
|