Open Existing Excel File

Mar 10, 2014 at 5:31 PM
Ok i guess i am not a very good searcher, thought I could find lots of examples of opening an existing excel file and filling in certain cells then showing to user.
  1. Open an existing file
  2. fill in certian cells.
  3. allow user to save to thier desktop.
here is what I have that keeps telling me I need a workbook first.
 protected void lnkExport_Click(object sender, EventArgs e)
    {
        var ExistFile = Server.MapPath("~/Excel/NSS.xlxs");

        var File = new FileInfo(ExistFile);


        using (ExcelPackage package = new ExcelPackage(File))
            {
                ExcelWorkbook workBook = package.Workbook;
                if (workBook != null)
                {
                    if (workBook.Worksheets.Count > 0)
                    {
                        ExcelWorksheet cSheet = workBook.Worksheets.First();

                        cSheet.Cells["A8"].Value = "Kevin";
                    }
                }
               
                package.Save();


                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                Response.AddHeader("Content-Disposition", "attachment; filename=ProposalRequest.xslx");
                Response.BinaryWrite(package.GetAsByteArray());
                // myMemoryStream.WriteTo(Response.OutputStream); //works too
                Response.Flush();
                Response.Close();
            }
   
    }
Mar 10, 2014 at 5:40 PM
Edited Mar 10, 2014 at 5:41 PM
Ok, I had the file extension wrong, what a dummy. However I can now get at the file but I get another error. Inthat It cannot touch file becuase its in use by another process. when trying to save it. Is there a way to create a copy of the existing file instead of using the current one and then saving it as another file that a user can save to their desktop after I have edited and added the contect I need to..
 protected void lnkExport_Click(object sender, EventArgs e)
    {
        var ExistFile = Server.MapPath("~/Excel/NSS.xlsx");

        var File = new FileInfo(ExistFile);


        using (ExcelPackage package = new ExcelPackage(File))
            {
                package.Load(new FileStream(ExistFile, FileMode.Open));

                ExcelWorksheet workSheet = package.Workbook.Worksheets["Sheet1"];

                workSheet.Cells["A8"].Value = "kevin";

                package.Save();


                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                Response.AddHeader("Content-Disposition", "attachment; filename=ProposalRequest.xslx");
                Response.BinaryWrite(package.GetAsByteArray());
                // myMemoryStream.WriteTo(Response.OutputStream); //works too
                Response.Flush();
                Response.Close();
            }
   
    }