I am trying to export a list to a CSV file. I got it all working up to the point I want to write to file to the response stream. This doesn\'t do anything.
Here is m
Respect to Biff, here's a few tweaks that let me use the method to bounce CSV from jQuery/Post against the server and come back as a CSV prompt to the user.
[Themed(false)]
public FileContentResult DownloadCSV()
{
var csvStringData = new StreamReader(Request.InputStream).ReadToEnd();
csvStringData = Uri.UnescapeDataString(csvStringData.Replace("mydata=", ""));
return File(new System.Text.UTF8Encoding().GetBytes(csvStringData), "text/csv", "report.csv");
}
You'll need the unescape line if you are hitting this from a form with code like the following,
var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val(data);
$('#downloadForm').append($(input));
$("#downloadForm").submit();
Simple excel file create in mvc 4
public ActionResult results() { return File(new System.Text.UTF8Encoding().GetBytes("string data"), "application/csv", "filename.csv"); }
I Think you have forgot to use
Response.Flush();
under
Response.Write(sw);
please check
Even if you have resolved your issue, here is another one try to export csv using mvc.
return new FileStreamResult(fileStream, "text/csv") { FileDownloadName = fileDownloadName };
With MVC you can simply return a file like this:
public ActionResult ExportData()
{
System.IO.FileInfo exportFile = //create your ExportFile
return File(exportFile.FullName, "text/csv", string.Format("Export-{0}.csv", DateTime.Now.ToString("yyyyMMdd-HHmmss")));
}
From a button in view call .click(call some java script). From there call controller method by window.location.href = 'Controller/Method';
In controller either do the database call and get the datatable or call some method get the data from database table to a datatable and then do following,
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
}
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SqlExport"+DateTime.Now+".csv");
Response.Charset = "";
//Response.ContentType = "application/text";
Response.ContentType = "application/x-msexcel";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}