C# Export DataTable to CSV File


C# Export DataTable to CSV File

Convert DataTable to CSV file C#

In this blog post I will share source code for to Export a DataTable to Comma Separated File (.CSV) format in a simple way using ASP.Net, C#. Find the C sharp code below :-

Related Articles 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Export Datatable to CSV C# - Sample</title>
    <form id="form1" runat="server">
            <asp:Button ID="btnExport" runat="server" Text="Export To CSV" OnClick="btnExport_Click" />
export datatable to csv c# windows application, csharp export datatable csv, csv c# syntax, write datatable to csv, convert datatable to csv c#, c# export data to csv, c# dataset to csv, data table to csv
Convert DataTable to CSV C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    protected void btnExport_Click(object sender, EventArgs e)
        DataTable dtTable = new DataTable();
        DataRow dtRow;

        dtTable.Columns.Add("SNo", typeof(int));
        dtTable.Columns.Add("Address", typeof(string));

        for (int i = 0; i <= 9; i++)
            dtRow = dtTable.NewRow();
            dtRow[0] = i;
            dtRow[1] = "Address " + i.ToString();

        Response.ContentType = "Application/x-msexcel";
        Response.AddHeader("content-disposition", "attachment;filename=test.csv");

    private string ExportToCSVFile(DataTable dtTable)
        StringBuilder sbldr = new StringBuilder();
        if (dtTable.Columns.Count != 0)
            foreach (DataColumn col in dtTable.Columns)
                sbldr.Append(col.ColumnName + ',');
            foreach (DataRow row in dtTable.Rows)
                foreach (DataColumn column in dtTable.Columns)
                    sbldr.Append(row[column].ToString() + ',');
        return sbldr.ToString();
export a DataTable to Comma Separated File (CSV) format, DataTable to CSV file, export datatable to CSV format, exporting data to CSV/Excel file, data table how to
c# write datatable to csv file
I hope you will enjoy the development tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome. 

Also If you like this article, don't forget to share this article with your friends and colleagues.
C# Export DataTable to CSV File Reviewed by Ravi Kumar on 3:27 PM Rating: 5

No comments:

All Rights Reserved by Etechpulse © 2012 - 2017

Contact Form


Email *

Message *

Powered by Blogger.