Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi I'm using the following method to export a datatable to CSV:
C#
private void btnDownload_Click(object sender, EventArgs e)
{
    if (DB.ExportAllHouseDetails())
    {
        DataTable dt = DB.dsResults.Tables["tbl_HouseDetails"];

        //ExportCSV(dt, @"C:\Users\pmcma\Documents\Visual Studio 2012\Projects\Houses\Houses\bin\Debug\HouseList.csv"); // + DateTime.Now);
        ExportCSV(dt, @"C:\Houses\HouseList.csv");

        MessageBox.Show("Download Complete!");
    }
    else
    {
        MessageBox.Show("No data found.");
    }                    
}

public static void ExportCSV(DataTable dt, string fileName)
        {
            try
            {
                // Create the CSV file to which grid data will be exported.
                StreamWriter sw = new StreamWriter(fileName, false);
                // First we will write the headers.
                //DataTable dt = m_dsProducts.Tables[0];
                int iColCount = dt.Columns.Count;
                for (int i = 0; i < iColCount; i++)
                {
                    sw.Write(dt.Columns[i]);                    
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);

                // Now write all the rows.
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            sw.Write(dr[i].ToString());
                        }
                        if (i < iColCount - 1)
                        {
                            sw.Write(",");
                        }
                    }

                    sw.Write(sw.NewLine);
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }          


Thing is when I check the CSV file a currency field that should be £25000 is outputted as £21000 also any names with special chars are not outputted as expected for example Daithí is outputted as Daithí. Is there anyway to stop this from happening and force the CSV export to just dump the data as it is in the SQL Tables?
Posted

1 solution

Adding this when instantiating the StreamWriter solved the issue:
C#
StreamWriter sw = new StreamWriter(fileName, false, Encoding.GetEncoding("UTF-8"));
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900