I am trying to export excel and make it password protected.
My code is below.
But I get the error:
Excel has completed checking and restoring the file level.
Some parts of this book may have been repaired or discarded.
I DO NOT KNOW THAT I AM WRONG.
In case I do this without saving the As string for the package, this error does not appear.
In my controller:
[HttpGet] public FileStreamResult ExportToExcel() { _objService = new ServiceBAL(); List<ReconcilationEntity> Objmodel = new List<ReconcilationEntity>(); Objmodel = _objService.GetCreditsudharLeads(); String URL = string.Empty; if (!Directory.Exists(Server.MapPath("~/TempExcel"))) { System.IO.Directory.CreateDirectory(Server.MapPath("~/TempExcel")); } String Filepath = Server.MapPath("~/TempExcel"); string date = DateTime.Now.ToShortDateString().Replace("/", "_") + "_" + DateTime.Now.ToShortTimeString().Replace(" ", "_").Replace(":", "_").Trim(); String FileName = "Creditsudhar_" + date + ".xlsx"; Filepath = Filepath + "\\" + FileName; string[] columns = { "AffName", "AffPhone", "AffEmail", "ProductName", "ContactName", "Status", "CreatedOn", "Commission", "IsCommissionPaid", "Accountname", "AccountNumber", "BankName", "BankBranch", "IFSCCode", "PanNumber" }; var file = ExcelExportHelper.ExportExcel(ExcelExportHelper.ListToDataTable(Objmodel), Filepath, "Creditsudhar Reconcillation Sheet " + DateTime.Now.ToShortDateString(), true, columns); var memStream = new MemoryStream(file); return this.File(memStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", FileName); } public static string ExcelContentType { get { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } } public static DataTable ListToDataTable<T>(List<T> data) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); DataTable dataTable = new DataTable(); for (int i = 0; i < properties.Count; i++) { PropertyDescriptor property = properties[i]; dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType); } object[] values = new object[properties.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = properties[i].GetValue(item); } dataTable.Rows.Add(values); } return dataTable; } public static byte[] ExportExcel(DataTable dataTable, String Filepath, string heading = "", bool showSrNo = false, params string[] columnsToTake) { string fullPath = string.Empty; byte[] ret; DeleteUploadedFile(Filepath); String result = String.Empty; using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading)); int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3; if (showSrNo) { DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int)); dataColumn.SetOrdinal(0); int index = 1; foreach (DataRow item in dataTable.Rows) { item[0] = index; index++; } }