Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF8 not working in Excel

in my .net code i'm using

byte[] bytesToSend = System.Text.Encoding.UTF8.GetBytes(partialtorender);

then m writin it to excel

the text in "Hindi" Language is coming gibberish in generated excel, can you please suggest what to do?

System.IO.MemoryStream memStr = new System.IO.MemoryStream();

memStr.Write(bytesToSend, 0, bytesToSend.Length);

 memStr.Position = 0;

FileStreamResult result1 = new FileStreamResult(memStr, "application/ms-excel");

Response.AddHeader("content-disposition", "attachment; filename=" + "newExcelSheet" + ".xls");

return result1;
like image 706
1Mayur Avatar asked Dec 05 '25 10:12

1Mayur


1 Answers

Try emitting an UTF-8 preamble to indicate the correct encoding to Excel. Also .xls is a proprietary binary format. You cannot just use a string variable as in your code.

Here's an example with a CSV file export:

public ActionResult Index()
{
    var csv = "मानक हिन्दी;some other value";
    var data = Encoding.UTF8.GetBytes(csv);
    data = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
    var cd = new ContentDisposition
    {
        Inline = false,
        FileName = "newExcelSheet.csv"
    };
    Response.AddHeader("Content-Disposition", cd.ToString());
    return File(data, "text/csv");
}
like image 77
Darin Dimitrov Avatar answered Dec 08 '25 00:12

Darin Dimitrov