Link to home
Start Free TrialLog in
Avatar of alik13
alik13Flag for United States of America

asked on

Convert GRidView into EXCEL

I have the following problem:
My code converts datagrid to Excel fine.  However in run time when MS-Excel 2007 opens up with generated output the error (warning) dialog box appears: The file you are trying to open is in a different format then specified by the file extension. Do you want to open the file now?"

if I press "yes" then my generated Excel  opens up fine showing all the data, however my date type column is not in short date format.  So instead of 07/2007 it shows JUL-2007.

Here is the code:
   protected void btnToExcel_Click1(object sender, EventArgs e)
    {
 
            DataTable dt = Grid_DALC.GetDates(); // this line populates datatable
            GridView gv = new GridView();

           gv.DataSource = dt;
           gv.DataBind();

            Response.Clear();
            Response.ClearHeaders();
            Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Charset = "";
            Response.ContentType = "application/vnd.xls";
            Response.ContentType = "application/vnd.ms-excel";
       
            // here I tried to format date the way I need (MM/YYYY)
            string strStyle = "<style>.currency { mso-number-format:\\0022$\\0022\\#\\,\\#\\#0\\.00; }\n\n";
            strStyle += ".dateformat { mso-number-format:##/####; }";
            strStyle += " </style>";
           
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            this.ClearControls(gv);
            gv.RenderControl(hw);
            HttpContext.Current.Response.Write(strStyle);
           // Write the HTML back to the browser.
       
            HttpContext.Current.Response.Write(tw.ToString());

            //End the response.
            HttpContext.Current.Response.End();
    }

ASKER CERTIFIED SOLUTION
Avatar of Jeeva Subburaj
Jeeva Subburaj
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of alik13

ASKER

Thank you I will try it.