Click here to Skip to main content
15,885,695 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys, busy learning mvc and would like to generate a dynamic .csv file and output it to the response stream. Anyone to give ideas?

Thanks,
Morgs
Posted

1 solution

This link may help you in the logic to generate .csv file but you have to fit it into your mvc pattern.


protected void ExportToCSV(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = "select CustomerID, ContactName, City, PostalCode" +
" from customers";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.csv");
Response.Charset = "";
Response.ContentType = "application/text";


StringBuilder sb = new StringBuilder();
for (int k = 0; k < dt.Columns.Count; k++)
{
//add separator
sb.Append(dt.Columns[k].ColumnName + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
//add separator
sb.Append(dt.Rows[i][k].ToString().Replace(",", ";") + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
 
Share this answer
 
Comments
Morgs Morgan 17-Jan-12 6:25am    
Thanks will take a look. But please edit your code when posting an answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900