0

error message after converting datatable to excel in asp.net c#

below code i am using

 Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
    Response.ContentType = "application/ms-excel";
    DataTable dt = ds.Tables[0];
    string str = string.Empty;
    foreach (DataColumn dtcol in dt.Columns)
    {
        Response.Write(str + dtcol.ColumnName);
        str = "\t";
    }
    Response.Write("\n");
    foreach (DataRow dr in dt.Rows)
    {
        str = "";
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            Response.Write(str + Convert.ToString(dr[j]));
            str = "\t";
        }
        Response.Write("\n");
    }
    Response.End();

error message is

  ![Your trying to open different format or corrupted file ][2] 

enter image description here

its opening after clicking ok but i dnt want showing this message .... where i made error... thank you...

temp sun
  • 146
  • 1
  • 2
  • 10

1 Answers1

0

Your content type is wrong. You are creating a CSV output, not Excel. Change content type to text/csv and file extension to .csv.

How to use the CSV MIME-type?

Link to OpenXML SDK which let's you create any Office format: http://msdn.microsoft.com/en-us/library/office/bb448854%28v=office.15%29.aspx

Community
  • 1
  • 1
Darek
  • 4,687
  • 31
  • 47