padma
padma

Reputation: 1

the file you are trying to open is in a different format than specified by the file extension c# error when trying to open file in excel

the file you are trying to open is in a different format than specified by the file extension c# error when trying to open file in excel.

Here is my code:

private void Export2Excel(GridView GridView1, GridView GridView2)

{

Response.AddHeader("content-disposition",
"attachment;filename= " + filename + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //"application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

PrepareForExportExcel(GridView1, GridView2);


string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());


Response.OutputStream.Flush();
Response.OutputStream.Close();

}
catch (Exception ex)
{
lblError.Text = ex.Message;
}

}

Upvotes: 0

Views: 1073

Answers (1)

D Stanley
D Stanley

Reputation: 152624

This is an Excel "issue", not C#. Excel can open HTML documents but it will warn you if the underlying format is different than the file extension.

The best way to solve it is to use an excel library to generate a "real" excel document other then HTML and use the right filename extension (XLS for binary Excel files and XSLX for "XML" excel files)

Upvotes: 2

Related Questions