1

下面是我读取现有 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     
4

1 回答 1

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 
}
于 2013-01-03T08:35:40.130 回答