当另一个进程打开文件时写入 Excel 文件

Writing to Excel file when it's opened by another process

我想知道是否可以在文件打开时使用 C#/EPPlus 写入 Excel 文件。我在尝试使用我的程序编写时不断遇到异常,但我在网上找不到任何东西。

这是我必须附加到现有工作表的代码,它在未打开电子表格时工作正常

    public static void AppendExistingMailingWorkbook(string workSheet, string filePath, IList<MailingReportItem> reportData)
    {
        //create a fileinfo object of an excel file on the disk
        FileInfo file = new FileInfo(filePath);
        Object thisLock = new Object();

        lock (thisLock)
        {
            //create a new Excel package from the file
            using (ExcelPackage excelPackage = new ExcelPackage(file))
            {
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[workSheet];

                var rowToAppend = worksheet.Dimension.End.Row + 1;
                for (int i = 0; i < reportData.Count; i++, rowToAppend++)
                {
                    worksheet.Cells[rowToAppend, 1].Value = reportData[i].BatchDate.Date.ToString("MM/dd/yyyy");
                    worksheet.Cells[rowToAppend, 2].Value = reportData[i].BatchId;
                    worksheet.Cells[rowToAppend, 3].Value = reportData[i].FileName;
                    worksheet.Cells[rowToAppend, 4].Value = reportData[i].PageCount;
                    worksheet.Cells[rowToAppend, 5].Value = reportData[i].MailDate;
                }

                //save the changes
                excelPackage.Save();
            }
        }
    }

在Excel中设置要共享的工作簿。来自 office help:

  1. 在 Excel
  2. 中打开工作簿
  3. 单击“审阅”>“共享工作簿”
  4. 在“编辑”选项卡上,select“允许多个用户进行更改...”复选框。
  5. 在“高级”选项卡上,select 更改要用于跟踪和更新的选项,然后单击“确定”。
  6. 如果这是一个新工作簿,请在“文件名”框中键入一个名称。或者,如果这是现有工作簿,请单击“确定”保存工作簿。
  7. 如果工作簿包含指向其他工作簿或文档的链接,请验证链接并更新任何损坏的链接。
  8. 单击“文件”>“保存”。
  9. 完成后,- Shared 将出现在 Excel window 的顶部,文件名旁边。

文件将以非独占方式打开,允许其他人在 Excel 打开文件的同时对其进行编辑。