Code Tips

The free code tips, advice and tricks contained here are for the programme developer. The information contained here will help improve your programme skills. lets code less, code better. 

Our target: Small tips, solve big problems.

Export CSV with unicode content

Problem:
Response.Clear();
Response.Charset = String.Empty;
Response.ContentType = "text/csv";

Response.ContentEncoding = Encoding.UTF8;
Response.AddHeader("content-disposition", "inline; filename=" + fileName);

System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileName);
for (int i = 0; i < dataTable.Columns.Count; i++) {
streamWriter.Write(dataTable.Columns[ i ].ToString());
streamWriter.Write(",");
}
Response.Write(streamWriter.ToString());
Response.End();

It can export to a csv file, but content in this file is incorrect. DataTable contained unicode string ( Japanese language). How can I correct it? 

Tips:

You've got an encoding issue. The default encoding for StreamWriter is UTF8NoBOM. That encoding should properly encode Unicode characters. Your problem is likely located in the app you use to read the file. Maybe you can egg it into interpreting the file properly if it contains a BOM (byte order mark). Construct it like this:

new System.IO.StreamWriter(fileName, Encoding.UTF8);
12/11/2007 2:49:00 AM Category .Net

Back