Monday, 3 September 2012

Export Datatable to CSV using C#


 protected void Button1_ServerClick(object sender, EventArgs e)
    {
        DataTable dtnew = null;
        try
        {
            string filename = "Detail.csv";         

            dtnew = YourDataTable;         
            string csv = ToCSV(dtnew);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + "");
            Response.AddHeader("Content-Length", csv.Length.ToString());
            Response.Write(csv);
            Response.End();         
        }
        catch (OutOfMemoryException oex)
        {
            lblError.Text = "Sorry!Data is too large to export";
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

    public static string ToCSV(DataTable table)
    {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < table.Columns.Count; i++)
        {
            result.Append(table.Columns[i].ColumnName);
            result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
        }

        foreach (DataRow row in table.Rows)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(row[i].ToString());
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }
        }

        return result.ToString();
    }

No comments:

Post a Comment