编程语言
首页 > 编程语言> > 使用epplus C#更新现有工作簿

使用epplus C#更新现有工作簿

作者:互联网

我正在尝试将新工作表添加到现有工作簿中,代码运行正常,没有任何错误.但是更改没有更新到excel文件.
这是我的代码

string path = "C:\\TestFileSave\\ABC.xlsx";
FileInfo filePath = new FileInfo(path);
if (File.Exists(path)) 
{
    using(ExcelPackage p = new ExcelPackage()) 
    {
        using(stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)) 
        {
            p.Load(stream);
            ExcelWorksheet ws = p.Workbook.Worksheets.Add(wsName + wsNumber.ToString());
            ws.Cells[1, 1].Value = wsName;
            ws.Cells[1, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
            ws.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(184, 204, 228));
            ws.Cells[1, 1].Style.Font.Bold = true;
            p.Save();
        }
    }
}

解决方法:

流对象不与包关联.唯一的关系是它将你的调用中的字节复制到Load后,它们是分开的.

你甚至不需要使用流 – 更好的是让包自己处理它,如下所示:

var fileinfo = new FileInfo(path);
if (fileinfo.Exists)
{
    using (ExcelPackage p = new ExcelPackage(fileinfo))
    {
        //using (stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
        {
            //p.Load(stream);
            ExcelWorksheet ws = p.Workbook.Worksheets.Add(wsName + wsNumber.ToString());
            ws.Cells[1, 1].Value = wsName;
            ws.Cells[1, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
            ws.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(184, 204, 228));
            ws.Cells[1, 1].Style.Font.Bold = true;
            p.Save();
        }

    }

}

标签:c,excel,epplus-4
来源: https://codeday.me/bug/20190713/1446017.html