2013-01-03 65 views
1

下面是我的代碼讀取現有excel文件:無法讀取現有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  

回答

6

這是相當直接的,或者:

  • 第一次檢查,如果工作表中存在且僅當它不那麼執行代碼
  • 只是刪除現有工作表,如果它存在,並添加它再次與你的價值觀
  • 修改這些值現有工作表「內容」

嘗試是這樣的,也許:

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 
} 
+0

我想讀我的文件....其報告模板..我想tloo然後在編輯我的模板,並保存在同一文件夾... –

+0

第一個選項是好的,只需打開文件檢查工作表是否存在,是否存在編輯並保存,否則添加,編輯和保存。 – dutzu

+0

是啊...我有問題編輯文件...在哪裏我的代碼無法編輯..因爲它會拋出錯誤,一旦他發現文件...你可以分享任何示例代碼。謝謝。 –