Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#3.0 ASP.NET
After clicking on some button the page, i run some function to fetch the records in dg and pass dg to below function and filename.
 
private void ExportToExcel(string strFileName, DataGrid dg)
    {
 
HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Buffer = true;
 
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + strFileName + ".xls");
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
 
        HttpContext.Current.Response.Charset = "";
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
//dg is DataGrid records
        dg.RenderControl(htw);
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();}
when it promts to open the excel file then it shows below message
"The file you trying to open, 'filename.xls', is in a different format than specified by the file extension.Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?"
Yes | No | Help
Posted 26-Jun-12 19:58pm
Edited 26-Jun-12 20:02pm
v2

1 solution

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 645
1 OriginalGriff 335
2 CPallini 250
3 PIEBALDconsult 150
4 Fredrik Bornander 130
0 OriginalGriff 5,835
1 Sergey Alexandrovich Kryukov 5,198
2 CPallini 4,740
3 George Jonsson 3,167
4 Gihan Liyanage 2,470


Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 27 Jun 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100