23

I wanna make CSV file encoding UTF-8. Now, my CSV file cannot show Japanese Fonts. I want C# code to solve this problem.

1
  • Try posting the code you have. It's hard to debug code that we cannot see. Dec 17, 2010 at 3:05

3 Answers 3

45

SuSanda,
I'm not sure about your current code or your actual text you're trying to save, but this might get you in the right direction.

using(var sw = new StreamWriter("testfile_utf8.csv", false, Encoding.UTF8))
{
    sw.WriteLine("頼もう");
}

If you open that file in Excel, it will show the Japanese text as expected.
If you do not include the Encoding.UTF8 parameter, it will display gibberish.

I hope that's what you're looking for.

1
  • 5
    use: new UTF8Encoding(false) instead of Encoding.UTF8 if you want to avoid the BOM symbol
    – Horia Toma
    Jan 7, 2014 at 16:16
6

This code helps to text from a csv file to save it as a encoded csv file. To use it Call as below and save it.

GetCSVFileContent("Your_CSV_FileName")

protected byte[] GetCSVFileContent(string fileName)
        {
            StringBuilder sb = new StringBuilder();
            using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true))
            {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
                    sb.AppendLine(line);
                }
            }
            string allines = sb.ToString();


            UTF8Encoding utf8 = new UTF8Encoding();


            var preamble = utf8.GetPreamble();

            var data = utf8.GetBytes(allines);


            return data;
        }
1
  • Warn: preamble is not used. It was important to use preamble in my case, data must be concated from preamble+data: data=preamble .Concat(data).ToArray();
    – razon
    Sep 6, 2017 at 13:28
2
 StringBuilder sb = new StringBuilder();          


 var columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
 sb.AppendLine(string.Join(",", columnNames));

 foreach (DataRow row in dt.Rows)
 {
     var fields = row.ItemArray.Select(field => field.ToString()).ToArray();
     sb.AppendLine(string.Join(",", fields));
 }

 File.WriteAllText(fileName, sb.ToString(), Encoding.UTF8);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.