1

there is an Excel file on the server with one line in it. I'm trying to do next:

try
            {
                using (FileStream fs = new FileStream(System.Web.HttpContext.Current.Server.MapPath("/DiscountLog" + ".xlsx"), FileMode.OpenOrCreate))
                {
                    using (ExcelPackage pp = new ExcelPackage(fs))
                    {
                        ExcelWorksheet wss = pp.Workbook.Worksheets[1];
                        int CurrentRow = wss.Dimension.Rows + 1;
                        wss.Cells[CurrentRow, 1].Value = model.FirstName;
                        wss.Cells[CurrentRow, 2].Value = model.LastName;
                        wss.Cells[CurrentRow, 3].Value = model.DiscountCard;
                        wss.Cells[CurrentRow, 4].Value = model.PhoneNumber;
                        wss.Cells[CurrentRow, 5].Value = model.Email;
                        wss.Cells[CurrentRow, 6].Value = DateTime.Now.ToString();
                        pp.SaveAs(fs);
                    }
                }
            }
            catch (Exception)
            {

            }

There is no error in the process, however when I try to open the file, I ask it to restore it.

2
  • This might be obvious to you, but how are you sure there isn't an error when you are swallowing all exceptions, and not doing anything with the error information? Commented Oct 26, 2017 at 13:04
  • I've removed try catch-block. Th main reason is that this package didnt work in streams with existing files. Answer will be below. Commented Oct 26, 2017 at 13:24

1 Answer 1

1

The correct code is:

var fileinfo = new FileInfo(System.Web.HttpContext.Current.Server.MapPath("/DiscountLog" + ".xlsx"));
            if (fileinfo.Exists)
            {
                using (ExcelPackage pp = new ExcelPackage(fileinfo))
                {
                    ExcelWorksheet wss = pp.Workbook.Worksheets[1];
                    int CurrentRow = wss.Dimension.Rows + 1;
                    wss.Cells[CurrentRow, 1].Value = model.FirstName;
                    wss.Cells[CurrentRow, 2].Value = model.LastName;
                    wss.Cells[CurrentRow, 3].Value = model.DiscountCard;
                    wss.Cells[CurrentRow, 4].Value = model.PhoneNumber;
                    wss.Cells[CurrentRow, 5].Value = model.Email;
                    wss.Cells[CurrentRow, 6].Value = DateTime.Now.ToString();
                    pp.Save();
                }
            }
            else
            {
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.