-1

I am using the EPPlus package to export an Excel 2007 file from a datatable, but I want to save the Excel file that I have created on the server. I am using this method:

private string SaveExcelFile(DataTable dt)
        {
            string reportName = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss-fff") + ".xlsx";

           Response.Clear();
           Response.Charset = "";
           Response.ContentEncoding = System.Text.Encoding.UTF8;
           Response.Cache.SetCacheability(HttpCacheability.NoCache);
           Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
           Response.AddHeader("content-disposition", "attachment;filename=\"" + reportName + "\"");

           using(ExcelPackage pck = new ExcelPackage())
           {
             ExcelWorksheet wsDt = pck.Workbook.Worksheets.Add("Sheet1");
             wsDt.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.None);
             wsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();

             //Response.BinaryWrite(pck.GetAsByteArray());
             string filePhysicalPath = Server.MapPath("~/Uploads/PeriodsReports/" + reportName);
             System.IO.File.WriteAllBytes(filePhysicalPath, pck.GetAsByteArray());
           }

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

           return reportName;
        }

After Excel has saved, I got this error:

Excel can't open the file because the file format or file extension is not valid

d219
  • 2,707
  • 5
  • 31
  • 36
Ahmad Alaa
  • 767
  • 9
  • 30
  • Don't you think that error also have to be posted in the question ?! – Disappointed Aug 03 '15 at 11:56
  • i edited my question, sorry, i changed the line of error, but i faces another one – Ahmad Alaa Aug 03 '15 at 12:05
  • It's strange behavior ... I had `excel can't open the file because the file format or file extension is not valid` when i used `WriteAllText` and it was resolved by `WriteAllBytes`. Are you sure that you open file which was saved by `WriteAllBytes` method ? Maybe you missed up something? – Disappointed Aug 03 '15 at 12:42
  • I don't know the reason of this error If you are sure that you didn't miss up anything. You can try just another approach from [here](http://stackoverflow.com/questions/12912912/save-as-using-epplus) – Disappointed Aug 03 '15 at 12:43

1 Answers1

0

You cannot use WriteAllText for binary files.(and excel is binary file) Try this instead

System.IO.File.WriteAllBytes(filePhysicalPath, pck.GetAsByteArray());
Disappointed
  • 1,100
  • 1
  • 9
  • 21
  • i used this line but when opening saved excel file, this message appears : excel can't open the file because the file format or file extension is not valid – Ahmad Alaa Aug 03 '15 at 11:53