Generate CSV file in ASP.Net Generate CSV file in ASP.Net asp.net asp.net

Generate CSV file in ASP.Net


I am not exactly sure what you are aiming for here, so I have assumed that you are wanting to create a CSV file in a button click event and send that back to the user. What you currently have appears to write the HTML of the control into an XLS file.

Try this:

protected void Button1_Click(object sender, EventArgs e){    var dataTable = GetData();    StringBuilder builder = new StringBuilder();    List<string> columnNames = new List<string>();    List<string> rows = new List<string>();    foreach (DataColumn column in dataTable.Columns)    {        columnNames.Add(column.ColumnName);     }    builder.Append(string.Join(",", columnNames.ToArray())).Append("\n");    foreach (DataRow row in dataTable.Rows)    {        List<string> currentRow = new List<string>();        foreach (DataColumn column in dataTable.Columns)        {            object item = row[column];            currentRow.Add(item.ToString());        }        rows.Add(string.Join(",", currentRow.ToArray()));    }    builder.Append(string.Join("\n", rows.ToArray()));    Response.Clear();    Response.ContentType = "text/csv";    Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");    Response.Write(builder.ToString());    Response.End();}

When I run this I am prompted by the browser to save the CSV file.

Edit:

If you would like to maintain your current approach (which is producing HTML, not CSV) then try this:

Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.xls");

Note that I have simply changed the file extension from CSV to XLS. When using the CSV extension, the text appeared in Excel as HTML. Using XLS, it appears just as it does when the above line is commented out.


Same as NickW's solution, but more concisely using LINQ:

//Append column namesbuilder.Append(String.Join(",",     from DataColumn c in dataTable.Columns    select c.ColumnName)).Append("\n");//Append data from datatablebuilder.Append(string.Join("\n",     from DataRow row in dataTable.Rows    select String.Join("\n",         String.Join(",", row.ItemArray)    )));Response.Clear();Response.ContentType = "text/csv";Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");Response.Write(builder.ToString());Response.End();


Finally I think i figured it out, we need to write a http handler if we intend to generate excel files on asp.net pages, now my button_click just redirects to TestHandler.ashx page and it renders the excel file. :)

Thank you very much all you guyz

public class TestHandler : IHttpHandler{    public void ProcessRequest(HttpContext context)    {        StringWriter textWriter = new StringWriter();        Html32TextWriter htmlTextWriter = new Html32TextWriter(textWriter);        DataGrid dg = new DataGrid();        dg.DataSource = GetData();        //Get the html for the control        dg.EnableViewState = false;        dg.DataBind();        dg.RenderControl(htmlTextWriter);        //Write the HTML back to the browser.        context.Response.Clear();        //context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=test.csv"));        //context.Response.ContentType = "text/csv";        context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=abc.xls"));        context.Response.ContentType = "application/vnd.ms-excel";        context.Response.Write(textWriter.ToString());        context.Response.End();    }    public bool IsReusable    {        get        {            return false;        }    }}