C# & ASP.NET: output CSV file with UTF-8 encoding and BOM ( MS Excel friendly )

Trabla: C# & ASP.NET:  output CSV file with UTF-8 encoding and BOM.

Excel correctly opens such CSV files.

Solving:

         /// <summary>
        /// Return CSV utf-8 file
        /// </summary>
        /// <returns></returns>
        public FileResult DownloadCSV( )
        {
           
            string lvCSV = " .... your CSV FILE STRING WITH utf-8 signs like こんにちは世界 ... ";

            string lvFileName = "myfile.csv";

            // UTF8 with BOM (byte order mark)
            UTF8Encoding lvUtf8EncodingWithBOM = new UTF8Encoding(true,true);

            // Byte Order Mark -  \x00EF\x00BB\x00BF
            string lvBOM =
            Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());

            return File( lvUtf8EncodingWithBOM.GetBytes( lvBOM + lvCSV), "text/csv;charset=utf-8", lvFileName);
        }
    }


No comments:

Post a Comment