Dot Net KB

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); 

1/25/2008 2:21:00 AM Published by FengLiN Category ASP.NET Comments 0 Views (466)
Name

Web site

Are you human? Enter the verify code below.

Comment