Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am using below code to export data to excel from datatable.But when i download it is showing ????????????.I had UTF8 encoding but it's not working.Can anyone help me out?

What I have tried:

C#
public void ExportToExcel(DataTable dt)
{
    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
    Response.ContentType = "application/ms-excel";
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    Response.Charset = "";
    DataTable dt1 = dt;
    string str = string.Empty;
    foreach (DataColumn dtcol in dt1.Columns)
    {
        Response.Write(str + dtcol.ColumnName);
        str = "\t";
    }
    Response.Write("\n");
    foreach (DataRow dr in dt1.Rows)
    {
        str = "";
        for (int j = 0; j < dt1.Columns.Count; j++)
        {
            Response.Write(str + Convert.ToString(dr[j]));
            str = "\t";
        }
        Response.Write("\n");
    }
    Response.End();
}
Posted
Updated 27-May-17 23:10pm
v2

For starters you are not really exporting anything to Excel. You are exporting to an HTML file with an xls extension. Excel can display HTML data which is why you can open this file.

You should look at options like EPPlus or the Open XML SDK for truly exporting data to Excel.
 
Share this answer
 
Please replace the following lines

Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Charset = "";

in your code with

Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
 
Share this answer
 
Comments
Member 11367004 12-Oct-18 7:47am    
Great !!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900