使用EPPlus Excel。保存文件后出错

时间:2017-10-26 12:04:27

标签: .net file filestream epplus

服务器上有一个Excel文件,其中包含一行。我正在尝试下一步:

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)
            {

            }

此过程中没有错误,但是当我尝试打开文件时,我要求它恢复它。

1 个答案:

答案 0 :(得分:1)

正确的代码是:

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
            {
            }