换工作表在 excel 工作簿 c#

标签: Asp.net Excel C#
发布时间: 2017/2/25 3:24:50
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

例如,看到的图像

enter image description here

我想要换工作表"Sheet1""Sheet3"。

我使用 EPPlus 的代码︰

            ExcelPackage masterPackage = new ExcelPackage();
            foreach (var file in files)
            {
                ExcelPackage pckg = new ExcelPackage(new FileInfo(file));

                foreach (var sheet in pckg.Workbook.Worksheets)
                {
                    //check name of worksheet, in case that worksheet with same name already exist exception will be thrown by EPPlus

                    string workSheetName = sheet.Name;
                    foreach (var masterSheet in masterPackage.Workbook.Worksheets)
                    {
                        if (sheet.Name == masterSheet.Name)
                        {
                            workSheetName = string.Format("{0}_{1}", workSheetName, DateTime.Now.ToString("yyyyMMddhhssmmm"));
                        }
                    }

                    //add new sheet

                    if (sheet.Name.Contains("MB_STORE_POTENTIALvsWALLET"))
                    {
                        masterPackage.Workbook.Worksheets.Add(workSheetName, sheet);

                    }
                    else
                    {
                        masterPackage.Workbook.Worksheets.Add(workSheetName, sheet);
                        masterPackage.Workbook.Worksheets.MoveToStart(1);
                    }
                }
            }
            masterPackage.SaveAs(new FileInfo(resultFile));

如何做到这一点?任何建议请。

解决方法 1:

这正常工作︰

ExcelPackage masterPackage = new ExcelPackage();
foreach (var file in files)
{
    ExcelPackage pckg = new ExcelPackage(new FileInfo(file));
    foreach (var sheet in pckg.Workbook.Worksheets)
    {
        //check name of worksheet, in case that worksheet with same name already exist exception will be thrown by EPPlus
        string workSheetName = sheet.Name;
        foreach (var masterSheet in masterPackage.Workbook.Worksheets)
        {
            if (sheet.Name == masterSheet.Name)
            {
                workSheetName = string.Format("{0}_{1}", workSheetName, DateTime.Now.ToString("yyyyMMddhhssmmm"));
            }
        }

        //add new sheet
        if (sheet.Name.Contains("MB_STORE_POTENTIALvsWALLET"))
        {
             masterPackage.Workbook.Worksheets.Add(workSheetName, sheet);
        }
        else
        {
             masterPackage.Workbook.Worksheets.Add(workSheetName, sheet);
             masterPackage.Workbook.Worksheets.MoveBefore(2, 1);
        }
    }
}
masterPackage.SaveAs(new FileInfo(resultFile));
官方微信
官方QQ群
31647020