EPPlus不能保存工作表的更改

4
我有一个批处理作业,它通过循环遍历电子表格逐行处理每个记录。根据结果,我想在每个记录的最后一列中留下评论。
当程序运行时,通过监视此单元格中的值,我可以知道适当的更改正在进行。但是,在运行.Save()函数后,我打开电子表格,发现每列看起来与程序运行之前完全相同。
看起来他们构建了EPPlus以便于保存您的更改,所以我不确定自己做错了什么。
以下是我打开电子表格的方法:
if (File.Exists(path))
{
    try
    {
        //Connect to spreadsheet
        FileStream _stream = File.Open(path, FileMode.Open, FileAccess.ReadWrite);
        FileInfo file = new FileInfo(path);

    }
    catch (IOException)
    {
        SendEmail.OkMail("Spreadsheet is currently in use. Please close and try again.");

        //Exit program
        Environment.Exit(0);
    }

    //Pull data into EPPlus object
    _package = new ExcelPackage();
    _package.Load(_stream);
    _sheet = _package.Workbook.Worksheets.First(); 
}
else
{
    //Notify user and exit program
    SendEmail.OkMail("Cannot find file in requested directory. Please check and try again.");

    //Exit program
    Environment.Exit(0);
}

这段代码会做出相应的更改。通过查看代码,我可以发现正确的值被存储在正确的ExcelWorkSheet对象命名为_sheet的单元格中。

//Figure out what type of update occurred
if (ignore == (_noUpdates - 1))
{
    _sheet.Cells[row, col + 11].Value = "Ignore";
}
else if (add == (_adds - 1))
{
    _sheet.Cells[row, col + 11].Value = "Valid Add";
}
else if (update == (_updates - 1))
{
    _sheet.Cells[row, col + 11].Value = "Valid Update";
}
else if (autoterm == (_autotermed - 1))
{
    _sheet.Cells[row, col + 11].Value = "Valid Autoterm";
} 

当我循环浏览电子表格后,我调用.Save()函数。然而这里没有任何变化发生。更改没有被保存。

//Save changes to spreadsheet.
_package.Save();
1个回答

8
Load(Stream) 方法不存储文件路径,也不存储传入的流以便在保存时重复使用。当调用 Save() 方法时,包不知道要保存文件在哪里,只是关闭了包。
(这似乎是一个糟糕的设计;在这种情况下,它应该抛出异常。)
尝试更改您的代码,使用带有 FileInfo 参数的构造函数:
FileInfo file = new FileInfo(path);
if (file.Exists)
{
    try
    {
        _package = new ExcelPackage(file);
        _sheet = _package.Workbook.Worksheets.First();
    }
    catch (IOException)
    {
        SendEmail.OkMail("Spreadsheet is currently in use. Please close and try again.");

        //Exit program
        Environment.Exit(0);
    }
}
else
{
    //Notify user and exit program
    SendEmail.OkMail("Cannot find file in requested directory. Please check and try again.");

    //Exit program
    Environment.Exit(0);
}

1
这个很好用。不过需要摆脱FileStream对象,就像你在代码中所做的那样。谢谢! - NealR
我有FileInfo,但它无法保存。 - user8599026
@MuhammedYILMAZ 没有看到你的代码,无法回答。同时,EPPlus 的最新版本已经发生了重大变化,所以这个答案可能已经不适用了。 - Richard Deeming
https://stackoverflow.com/questions/65360811/i-use-epplus-in-aspnet-i-can-read-data-but-i-cannot-write-to-existing-file-fi?noredirect=1#comment115560956_65360811 - user8599026

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接