使用EPPlus打开Excel文档

24

我正在尝试使用EPPlus引用/包打开一个Excel文档,但我无法打开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);,但它不允许...


你想在Excel中打开电子表格吗? - matthewr
是的,这就是我想做的,我只想让它显示出来,这样我就可以开始学习和使用它了... - Code Ratchet
bool.xls 是一个简单的 Excel 电子表格,位于我的桌面上。 - Code Ratchet
2个回答

34

尝试这个:

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");
}

希望这可以帮助你!


我使用了你们的样例,但是出现了错误... System.InvalidOperationException: 工作簿中已经存在一个同名工作表,在OfficeOpenXml.ExcelWorksheets.Add(String Name)处。 - chinna_82

1

尝试在ASP NET Core中使用以下方法以避免win32异常:

private void CreateWorkbook(string fileName)
{
    using (var p = new ExcelPackage())
    {
        p.Workbook.Properties.Author = "Barry Guvenkaya";
        p.Workbook.Properties.Title = "MyTitle";
        p.Workbook.Worksheets.Add("MySheet");
        var bin = p.GetAsByteArray();
        File.WriteAllBytes(fileName, bin);

        // Below code opens the excel doc
        var proc = new Process();
        proc.StartInfo = new ProcessStartInfo(fileName)
        {
            UseShellExecute = true
        };
        proc.Start();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接