Responsive Ads Here

Thursday, December 27, 2012

The file you are trying to open "aaa.xls" in a different format than specified file extension.

Sometimes it is necessary to provide the functionality to download a Tabular report into Excel. When you are using a simple Grid View and want to export it to the Excel. Most of the time the code used for exporting to Excel is like:


attachment = "attachment; filename=" + fileName + ".xls"; //Setting the attachment name.  
 Response.ClearContent(); //clears all content output from the buffer stream.  
           Response.AddHeader("content-disposition", attachment);  
           Response.ContentType = "application/vnd.ms-excel";  
           using (StringWriter sw = new StringWriter())  
           {  
             using (HtmlTextWriter htw = new HtmlTextWriter(sw))  
             {  
               using (HtmlForm frm = new HtmlForm())  
               {  
                 this.pnl1.Parent.Controls.Add(frm);  
                 frm.Controls.Add(this.pnl1);  
                 frm.RenderControl(htw);  
                 Response.Write(sw.ToString());  
                 Response.End();  
               }  
             }  
           }  

For writing to an Excel file on stream since this will give you the following message when you open the excel file.

Web1.gif


Microsoft has provided the solution to this problem, suggesting to edit the Group Security setting. After updating the registry setting you'll not receive this error.
But this is not possible when you are serving a public website.
So I found a solution for this problem of how you can use an open source library to create an Excel without using the Microsoft InterOp library to create the Excel file.
You can download the dll by clicking here . 


 using OfficeOpenXml;  
 using OfficeOpenXml.Style;  
 private void ExportExcel(DataTable dt)  
     {  
       using (ExcelPackage pck = new ExcelPackage())  
       {  
         //Create the worksheet  
         ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Book1"); //set Worksheet Name  
         //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1  
         ws.Cells["A1"].LoadFromDataTable(dt, true);  
         //prepare the range for the column headers  
         string cellRange = "A1:" + Convert.ToChar('A' + dt.Columns.Count - 1) + 1;  
         //Format the header for columns  
         using (ExcelRange rng = ws.Cells[cellRange])  
         {  
           rng.Style.WrapText = false;  
           rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;  
           rng.Style.Font.Bold = true;  
           rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid  
           rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(80, 124, 209));  
           rng.Style.Font.Color.SetColor(System.Drawing.Color.White);  
         }  
         //prepare the range for the rows  
         string rowsCellRange = "A2:" + Convert.ToChar('A' + dt.Columns.Count - 1) + dt.Rows.Count * dt.Columns.Count;  
         //Format the rows  
         using (ExcelRange rng = ws.Cells[rowsCellRange])  
         {  
           rng.Style.WrapText = false;  
           rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;  
           rng.Style.Font.Bold = true;  
           rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid  
           rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.White);  
           rng.Style.Font.Color.SetColor(System.Drawing.Color.Black);  
         }  
         //Read the Excel file in a byte array  
         Byte[] fileBytes = pck.GetAsByteArray();  
         //Clear the response  
         Response.Clear();  
         Response.ClearContent();  
         Response.ClearHeaders();  
         Response.Cookies.Clear();  
         //Add the header & other information  
         Response.Cache.SetCacheability(HttpCacheability.Private);  
         Response.CacheControl = "private";  
         Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;  
         Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;  
         Response.AppendHeader("Content-Length", fileBytes.Length.ToString());  
         Response.AppendHeader("Pragma", "cache");  
         Response.AppendHeader("Expires", "60");  
         Response.AppendHeader("Content-Disposition",  
         "attachment; " +  
         "filename=\"ExcelReport.xlsx\"; " +  
         "size=" + fileBytes.Length.ToString() + "; " +  
         "creation-date=" + DateTime.Now.ToString("R") + "; " +  
         "modification-date=" + DateTime.Now.ToString("R") + "; " +  
         "read-date=" + DateTime.Now.ToString("R"));  
         Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";  
         //Write it back to the client  
         Response.BinaryWrite(fileBytes);  
         Response.End();  
       }  
     }  
     protected void btnExcelExport_Click(object sender, EventArgs e)  
     {  
       DataTable dtt = (DataTable)Session["Datasource"];  
       ExportExcel(dtt);  
     } 

1 comment: