Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Iam getting when export to excel in asp.net

The file you are trying to open is in a different format than specified by the file extension

C#
Response.ClearContent();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=Test.xls");

            GridView excel = new GridView();
            excel.DataSource = dt;
            excel.DataBind();
            excel.RenderControl(new HtmlTextWriter(Response.Output));

            Response.Flush();
            Response.End();


Thanks,
Krishna
Posted
Updated 25-Jun-13 20:54pm
v2

Follow below steps:

1) Start Registry Editor.(run regedit.exe)

2) If you are prompted for an administrator password or for a confirmation, type the password, or click Continue.

3) Locate and then click the following registry subkey:

HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security

4) On the Edit menu, point to New, and then click DWORD Value.

5) Type ExtensionHardening, and then press ENTER.

6) Right-click ExtensionHardening, and then click Modify.

7) In the Value data box, type 0, and then click OK.

You are done.

:doh:[Another workaround]:

ClosedXML - The easy way to OpenXML[^]

[Update]:

Excel 2007 Extension Warning On Opening Excel Workbook from a Web Site[^]


Regards.. :laugh:
 
Share this answer
 
v3
Comments
Krishna KV 26-Jun-13 5:36am    
After changing the registry, it working fine. no error message while opening excel in server machine. but trying in client machine getting same error
Thanks7872 26-Jun-13 6:08am    
Refer to updated answer to know whats happening and what can be done.
C#
ds = //fill your dataset ds
        DataTable dt = new DataTable();
        dt = ds.Tables[0];
        string attachment = "attachment; filename=//givefilename";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/vnd.ms-excel";
        string tab = "";
        foreach (DataColumn dc in dt.Columns)
        {
            Response.Write(tab + dc.ColumnName);
            tab = "\t";
        }
        Response.Write("\n");
        int i;
        foreach (DataRow dr in dt.Rows)
        {
            tab = "";
            for (i = 0; i < dt.Columns.Count; i++)
            {
                Response.Write(tab + dr[i].ToString());
                tab = "\t";
            }
            Response.Write("\n");
        }
        Response.End();
 
Share this answer
 
v2
Comments
Krishna KV 26-Jun-13 5:37am    
Same error The file you are trying to open is in a different format than specified by the file extension.

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