1
  private static ExcelPackage MergeExcelPackages(ExcelPackage aExcelPackage,
                ExcelPackage bExcelPackage)
     {
     var excelPackage = new ExcelPackage();
     excelPackage.Workbook.Worksheets.Add("AInfo", aExcelPackage.Workbook.Worksheets[1]);
     excelPackage.Workbook.Worksheets.Add("BInfo", bExcelPackage.Workbook.Worksheets[1]);

     return excelPackage;
     }

上面的代码在 EPPlus 3.1.3.3 中有效,但在 vesion 4.0.4 中无效。它抛出以下错误:

System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at OfficeOpenXml.ExcelStyleCollection`1.get_Item(Int32 PositionID)
   at OfficeOpenXml.Style.ExcelStyle.get_XfId()
   at OfficeOpenXml.ExcelStyles.CreateNamedStyle(String name, ExcelStyle Template)
   at OfficeOpenXml.ExcelStyles.CloneStyle(ExcelStyles style, Int32 styleID, Boolean isNamedStyle, Boolean allwaysAdd)
   at OfficeOpenXml.ExcelStyles.CloneStyle(ExcelStyles style, Int32 styleID)
   at OfficeOpenXml.ExcelWorksheets.CloneCells(ExcelWorksheet Copy, ExcelWorksheet added)
   at OfficeOpenXml.ExcelWorksheets.Add(String Name, ExcelWorksheet Copy)
4

1 回答 1

1

这是我认为可以实现您的目标的完整方法。我正在使用 EPPlus 4.0.4

public bool CreateJobReports(int jobId, string jobName, string destination,
    Dictionary<string, DataTable> reportTables)
{
    try
    {
        var tables = reportTables.Count;
        var worksheets = 0;
        var workBookName = String.Format("JobReports_JobId_{0}", jobId);
        var fullPath = String.Format(@"{0}\{1}.xlsx", destination, workBookName);
        var excelWorkbook = new FileInfo(fullPath);
        using (var package = new ExcelPackage(excelWorkbook))
        {
            foreach (var table in reportTables)
            {
                var tableName = table.Key;
                var reportTable = table.Value;

                // Add a new worksheet.
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(tableName);

                // Load the data into the worksheet starting from top left (A1).
                worksheet.Cells["A1"].LoadFromDataTable(reportTable, true, TableStyles.None);
            }

            package.Save();

            worksheets = package.Workbook.Worksheets.Count;
        }

        return worksheets == tables;
    }
    catch (Exception ex)
    {
        var jobInfo = string.Format("JobId: {0}, JobName: {1}. ", jobId, jobName);
        var exception = jobInfo + ex.ToString();
        if (ex.InnerException != null)
        {
            exception = exception + String.Format(". Inner exception: {0}", ex.InnerException.ToString());
        }
        _logger.Fatal(mapInfo + exception);

        throw;
    }
}
于 2015-11-13T15:58:09.763 回答