我想知道在打开文件时是否可以使用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:
- Shared
将出现在Excel窗口的顶部,文件名旁边。然后,该文件将以非排他性方式打开,允许其他人在Excel打开时对其进行编辑。