Friday, February 8, 2013

Create CSV file from a DataTable in CSharp (C#)

While working as a .net programmer you may getting a requirement to convert a DataTable to CSV file format.

CSV - Comma Separated Value. Tabular format data are converted into comma separated values text file with the extension of csv. See sample below

Name, Age, Eid, Native
Raj, 27, E0025, Chennai 
Kumar, 20, E0032, Nagercoil
Balu, 22, E0024, Mumbai
Raj, 25, E0026, Bangalore

To achieve this in C#

public void CreateCSVFile(DataTable dt, string strFilePath)  
{  
    try  
    {  
        StreamWriter sw = new StreamWriter(strFilePath, false);  
        int columnCount = dt.Columns.Count; 
 
        for (int i = 0; i < columnCount ; i++)  
        {  
            sw.Write(dt.Columns[i]); 
 
            if (i < columnCount - 1)  
            {  
                sw.Write(",");  
            }  
        }  

        sw.Write(sw.NewLine);  
         
        foreach (DataRow dr in dt.Rows)  
        {  
            for (int i = 0; i < columnCount ; i++)  
            {  
                if (!Convert.IsDBNull(dr[i]))  
                {  
                    sw.Write(dr[i].ToString());  
                }  

                if (i < columnCount - 1)  
                {  
                    sw.Write(",");  
                }  
            }  

            sw.Write(sw.NewLine);  
        }  

        sw.Close();  
        }  
        catch (Exception ex)  
        {  
            throw ex;  
        }  
}  
Call the CreateCSVFile function like below by passing the DataTable to convert and the path of the CSV file to be saved.
static void Main(string[] args)
{
    CreateCSVFile(dt,"D://ConvertedFile.csv");
}

2 comments:

  1. Hey there terrific blog! Does running a blog such as this take a large amount of work?
    I have virtually no knowledge of coding however I had been hoping to start my own blog in the near future.
    Anyhow, if you have any suggestions or tips for new blog
    owners please share. I understand this is off subject but I
    simply needed to ask. Thank you!

    ReplyDelete