Click here to Skip to main content
15,886,026 members
Articles / Programming Languages / C#

How to Export Encoded Data into CSV Files

Rate me:
Please Sign up or sign in to vote.
4.80/5 (2 votes)
15 Mar 2013CPOL1 min read 43.3K   1.2K   9   3
How to export data using various encoding into CSV format

Introduction

Exporting data into various file formats - i.e., .csv, .tsv is frequently required in our day to day action. Many of us have written code segments for this too. My purpose in writing this article is to demonstrate How to export data using various encoding into CSV format.

Here I’ve developed a sample application which exports a Unicode data stored in database into CSV file. Note that if you export data with Unicode encoding delimited by coma (‘,’), it won’t give you effective results. Let’s start with how to overcome this problem.

Inside the Code

In the above image, you can see that DatagridView is loaded with data. This data contains data in Unicode format – Last two rows contains data in Chinese and Russian language. Also, we’ve an option for selecting various encoding and delimiters while exporting data. Code for file export is shown as below:

C#
privatevoid btnExport_Click(objectsender, EventArgs e)
{
    DataTabledt = dg.DataSource as DataTable;

    if(string.IsNullOrEmpty(txtPath.Text.Trim()))
    {
        ShowMessage("Invalid file path. Please enter valid file path");
        return;
    }

    StringBuilderbuilder = new StringBuilder();

    if(chkHeader.Checked)
    {
            varcount = 0;
        foreach(DataColumn column indt.Columns)
        {
            count++;
            stringcontent = column.ColumnName + "";
            content = content.Replace("\"", "\"\"");
            builder.Append(string.Format("{0}{1}{0}", Convert.ToChar(34), content));

            if(count < dt.Columns.Count)
                builder.Append(GetDelimeter(cmbDelimeter.Text.Trim()));
        }
        builder.Append(Environment.NewLine);
    }

    foreach(DataRow row indt.Rows)
    {
        for(int i = 0; i < row.ItemArray.Length; i++)
        {
            if(!Convert.IsDBNull(row[i]))
            {
                string content = row[i].ToString() + "";
                content = content.Replace("\"", "\"\"");
                builder.Append(string.Format("{0}{1}{0}", Convert.ToChar(34), content));

                     if(i < row.ItemArray.Length - 1)
                    builder.Append(GetDelimeter(cmbDelimeter.Text.Trim()));
            }
        }
        builder.Append(Environment.NewLine);
    }

    using (var streamWriter = newStreamWriter(txtPath.Text.Trim(), 
                  chkAppend.Checked, GetEncoding(cmbEncoding.Text.Trim())))
    {
        streamWriter.Write(builder.ToString());
        streamWriter.Flush();
        streamWriter.Close();
    }
    ShowMessage("Data successfully exported");
}

In the above code, you can see that we are iterating over each row in data table and appending each cell data into string builder. The delimiter that we choose while exporting is appended after each cell data through GetDelimeter() function. The code for GetDelimeter() function is shown below:

C#
private string GetDelimeter(stringdelimeter)
{
    stringretval = "";
    switch(delimeter.ToLower())
    {
        case"coma":
            retval = ",";
            break;
        case"tab":
            retval = "\t";
            break;
        case"space":
            retval = "\b";
            break;
    }
    returnretval;
}

After appending all data into string builder, initialize StreamWriter object with argument – Destination file path, data should be appended or not and content Encoding. Encoding is also chosen by us while exporting. Code for selecting encoding is given below:

C#
private Encoding GetEncoding(string encoding)
{
    Encodingencod = null;
    switch(encoding.ToLower())
    {
        case"unicode":
            encod = Encoding.Unicode;
            break;
        case"utf8":
            encod = Encoding.UTF8;
            break;
        case"ansi":
        default:
            encod = Encoding.Default;
            break;
    }

    returnencod;
}

In this way, we can export data in CSV file with the encoding that we choose.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Automation Anywhere Inc.
India India
I am Himanshu Manjarawala, Garduate in Computer Science and MCA From Veer Narmad South Gujarat University, Surat Gijarat India. Currently working as Sr. Software Developer in Automation Anywhere Softwares Pvt. Ltd. Vadodara, Gujarat

Comments and Discussions

 
SuggestionA few recommendations Pin
Andrew Rissing19-Mar-13 5:03
Andrew Rissing19-Mar-13 5:03 
GeneralRe: A few recommendations Pin
Himanshu Manjarawala3-Apr-13 23:15
Himanshu Manjarawala3-Apr-13 23:15 
Thanks Andrew for your precious comments. I'll change code accordingly.
Himanshu Manjarawala.
Sr. Software Engineer
http://www.himanshumbi.blogspot.com
http://www.fieredotnet.wordpress.com

QuestionNull column items Pin
George Swan17-Mar-13 6:37
mveGeorge Swan17-Mar-13 6:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.