简体   繁体   English

如何使用EPPlus将新工作表添加到现有的Excel文件中?

[英]How to add a new sheet to an exising Excel file with EPPlus?

Using EPPlus I want to add a new sheet to an Excel file but I do not want to delete the existing sheets in the file if any, and I want to insert it as the first sheet in the file. 使用EPPlus,我想向Excel文件中添加一个新图纸,但是我不想删除该文件中的现有图纸(如果有的话),并且想将其作为文件中的第一张图纸插入。 Here is what I have written for a quick test but it deletes all the existing sheets: 这是我为快速测试编写的内容,但是它删除了所有现有的工作表:

using (ExcelPackage p = new ExcelPackage())
{
    p.Workbook.Worksheets.Add("HubaHuba");
    p.Workbook.Worksheets.MoveToStart("HubaHuba");
    ExcelWorksheet ws = p.Workbook.Worksheets[1];
    ws.Name = "HubaHuba";

    var cell = ws.Cells[1, 1];
    cell.Value = "dfsdfsdfsd";
    cell = ws.Cells[1, 2];
    cell.Value = "347895y5 Oh";

    Byte[] bin = p.GetAsByteArray();
    File.WriteAllBytes(path,bin);
}

That's because you're rewriting the file with command File.WriteAllBytes . 那是因为您正在使用命令File.WriteAllBytes重写文件。 Instead you should just call p.Save() and ExcelPackage needs to use the constructor that accepts the file path. 相反,您应该只调用p.Save()并且ExcelPackage需要使用接受文件路径的构造函数。 Then it will work. 然后它将起作用。

using (ExcelPackage excelEngine = new ExcelPackage())
{
     excelEngine.Workbook.Worksheets.Add("sheet1");
     excelEngine.Workbook.Worksheets.Add("sheet2");
     excelEngine.Workbook.Worksheets.Add("sheet3");

     String myFile= "c:\....\xx.xlsx";
     excelEngine.SaveAs();

}

When you use Add the sheet is added at the and of current file sheets. 使用Add ,工作表将被添加到当前文件表和中。

If you want to add in a specific position use this function: 如果要添加到特定位置,请使用此功能:

excelEngine.Workbook.Worksheets.Add("sheet0");
excelEngine.Workbook.Worksheets.MoveBefore(4, 1);

sheet0 is added at the and in 4th position and you move it in first position with the previous code. sheet0被添加到和的第4个位置,并且您使用上一个代码将其移动到第一个位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM