无法读取现有的Excel文件

时间:2013-01-03 08:33:25

标签: c# epplus

以下是我阅读现有Excel文件的代码:

FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeExceptionReport.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
    var ws = xlPackage.Workbook.Worksheets.Add("Content");
    ws.View.ShowGridLines = false;
    ws.Column(4).OutlineLevel = 1;
    ws.Column(4).Collapsed = true;
    ws.Column(5).OutlineLevel = 1;
    ws.Column(5).Collapsed = true;
    ws.OutLineSummaryRight = true;
    //Headers
    ws.Cells["B1"].Value = "Name";
    ws.Cells["C1"].Value = "Size";
    ws.Cells["D1"].Value = "Created";
    ws.Cells["E1"].Value = "Last modified";
    ws.Cells["B1:E1"].Style.Font.Bold = true;
    System.Diagnostics.Process.Start("C:\\Excel\\SampleStockTakeExceptionReport.xlsx");
}

我运行代码时。它会引发运行时错误 错误。

System.InvalidOperationException: A worksheet with this name already exists in the workbook
at OfficeOpenXml.ExcelWorksheets.Add(String Name)
at Report.Form1.ExportToExcel1(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 43     

1 个答案:

答案 0 :(得分:7)

这很直接,或者:

  • 首先检查工作表是否存在,只有当工作表不存在时才执行您的代码
  • 只需移除现有工作表(如果存在),并使用您的值
  • 再次添加
  • 修改现有工作表“内容”
  • 的值

尝试类似这样的事情:

FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeExceptionReport.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
    //Check if worksheet with name "Content" exists and retrieve that instance or null if it doesn't exist       
    var ws = xlPackage.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Content");
    //If worksheet "Content" was not found, add it
    if (ws == null)
    {
       ws = xlPackage.Workbook.Worksheets.Add("Content");
    }

    //Rest of code 
}