Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

How to Export Encoded Data into CSV Files

, 15 Mar 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

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)

Share

About the Author

Himanshu Manjarawala
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
Follow on   Twitter   Google+

Comments and Discussions

 
SuggestionA few recommendations PinmemberAndrew Rissing19-Mar-13 6:03 
GeneralRe: A few recommendations PinmemberHimanshu Manjarawala4-Apr-13 0: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 [modified] PinmemberGeorge Swan17-Mar-13 7:37 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141216.1 | Last Updated 16 Mar 2013
Article Copyright 2013 by Himanshu Manjarawala
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid