2012-08-10 111 views
18

我想使用EPPlus參考/打包打開Excel文檔。我無法打開Excel應用程序。我錯過了什麼代碼?使用EPPlus打開Excel文檔

protected void BtnTest_Click(object sender, EventArgs e) 
{ 
    FileInfo newFile = new FileInfo("C:\\Users\\Scott.Atkinson\\Desktop\\Book.xls"); 

    ExcelPackage pck = new ExcelPackage(newFile); 
    //Add the Content sheet 
    var ws = pck.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; 
} 

我已經試過pck.open(newFile);,但不允許它...

+0

是否要在Excel中打開電子表格? – 3aw5TZetdf 2012-08-10 08:13:04

+0

是啊多數民衆贊成在即時嘗試做我只是想讓它顯示,所以我可以開始學習和使用它... – 2012-08-10 08:14:03

+0

bool.xls是一個簡單的Excel電子表格,坐在我的桌面 – 2012-08-10 08:14:42

回答

27

試試這個:

protected void BtnTest_Click(object sender, EventArgs e) 
{ 
    FileInfo newFile = new FileInfo("C:\\Users\\Scott.Atkinson\\Desktop\\Book.xls"); 

    ExcelPackage pck = new ExcelPackage(newFile); 
    //Add the Content sheet 
    var ws = pck.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; 

    pck.Save(); 
    System.Diagnostics.Process.Start("C:\\Users\\Scott.Atkinson\\Desktop\\Book.xls"); 
} 

希望這有助於!

+0

完美的謝謝:) – 2012-08-10 08:47:29

+0

我用你的示例,但它把我這個錯誤... System.InvalidOperationException:具有此名稱的工作表已存在於OfficeOpenXml.ExcelWorksheets.Add(字符串名稱)的工作簿 – 2013-01-03 08:08:10

+0

它仍然無法使用.xlsm文件 – 2016-12-15 19:04:33