Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to Export Encoded Data into CSV Files

4.80/5 (2 votes)
15 Mar 2013CPOL1 min read 43.7K   1.2K  
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)