Export DataTable to CSV / Excel

DataTable objDt = _dt;// where _dt is your DataTable with values to export

        if (objDt.Rows.Count <= 0)
        {
            lblMessage.Text = "No data to Download";
            lblMessage.ForeColor = System.Drawing.Color.Red;
            return;
        }

        HttpContext context = HttpContext.Current;

        context.Response.Clear();

        foreach (DataColumn column in objDt.Columns)
            context.Response.Write(column.ColumnName + ",");

        context.Response.Write(Environment.NewLine);

        foreach (DataRow row in objDt.Rows)
        {
            for (int i = 0; i < objDt.Columns.Count; i++)
                context.Response.Write(row[i].ToString() + ",");
            context.Response.Write(Environment.NewLine);
        }

        context.Response.ContentType = "text/csv";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
        context.Response.End();
OR
DataTable objDt = _dt;// where _dt is your DataTable with values to export

        if (objDt.Rows.Count <= 0)
        {
            lblMessage.Text = "No data to Download";
            lblMessage.ForeColor = System.Drawing.Color.Red;
            return;
        }

StreamWriter sw = new StreamWriter(@"D:\Test\test.csv", false);

        for (int i = 0; i < objDt.Columns.Count; i++)
        {
            sw.Write(objDt.Columns[i]);
            if (i < iColCount - 1)
                sw.Write(",");
        }
        sw.Write(sw.NewLine);

        foreach (DataRow dr in objDt.Rows)
        {
            for (int i = 0; i < objDt.Columns.Count; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                    sw.Write(dr[i].ToString());

                if (i < iColCount - 1)
                    sw.Write(",");
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();

Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)

1 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More