Click here to Skip to main content
15,892,965 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hello,
How to export and download csv file using c# asp.net web application?
i am using this code for export csv and download in local system:-
C#
SqlConnClass connClass = new SqlConnClass();
DataTable dt = connClass.GetQrCodeDetails();

        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();

but my code did its not creating a csv file its not downloading.
Please help me.
Thanks in Advance.

Ankit Agarwal
Software Engineer
Posted
Updated 22-Sep-15 23:46pm
v2
Comments
Is there any exception?
Agarwal1984 23-Sep-15 6:57am    
When we use try catch block its showing error:-
unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

when we did not use try catch, so it was not showing error.
Richard Deeming 23-Sep-15 8:44am    
Try removing the Response.Charset = ""; line, and changing the content type to text/csv.

Also, check for null values in your DataTable.

If you're getting an exception, you should be able to find the details in the application event log on the server.
Agarwal1984 23-Sep-15 9:00am    
Our data in this my DataTable but its not export and downloading.

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