Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EP Plus - Error Table range collides with table

Tags:

c#

excel

epplus

I am building an export to excel functionality using EP plus and c# application. I am currently getting the error.

'Table range collides with table tblAllocations29'

In my code logic below, I am looping through a data structure that contains key and collection as a value.

I looping across each key and once again loop through each collection belonging to that key.

I basically need to print tabular information for each collection along with its totals.

In the current scenario, I am getting the error when it is trying to print three arrays The first array has 17 records The second array has 29 records The third array has 6 records

I have taken a note of the ranges it is creating while debugging

The ranges are

A1  G18
A20 G50
A51 G58

controller

[HttpGet]
[SkipTokenAuthorization]
public HttpResponseMessage DownloadFundAllocationDetails(int id, DateTime date)
{
    var ms = GetStrategy(id);

    DateTime d = new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1);
    if (ms.FIRM_ID != null)
    {
        var firm = GetService<FIRM>().Get(ms.FIRM_ID.Value);
        IEnumerable<FIRMWIDE_MANAGER_ALLOCATION> allocationsGroup = null;
        var allocationsGrouped = GetAllocationsGrouped(EntityType.Firm, firm.ID, d);


         string fileName = string.Format("{0} as of {1}.xlsx", "test", date.ToString("MMM, yyyy"));
         byte[] fileContents;
         var newFile = new FileInfo(fileName);
         using (var package = new OfficeOpenXml.ExcelPackage(newFile))
         {
            FundAllocationsPrinter.Print(package, allocationsGrouped);
            fileContents = package.GetAsByteArray();
         }

         var result = new HttpResponseMessage(HttpStatusCode.OK)
         {
             Content = new ByteArrayContent(fileContents)
         };

         result.Content.Headers.ContentDisposition =
            new ContentDispositionHeaderValue("attachment")
            {
                 FileName = fileName
            };

         result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

         return result;
    }

    return null;

    #endregion
}

I have written the following utility that will try and export. It works sometimes when there are two array collections and it failed when processing three. Could somebody tell me what the problems are

FundsAllocationsPrinter.cs

public class FundAllocationsPrinter
{
    public static void Print(ExcelPackage package, ILookup<string, FIRMWIDE_MANAGER_ALLOCATION> allocation)
    {
        ExcelWorksheet wsSheet1 = package.Workbook.Worksheets.Add("Sheet1");
        wsSheet1.Protection.IsProtected = false;
        int count = 0;
        int previouscount = 0;
        var position = 2;
        int startposition = 1;
        IEnumerable<FIRMWIDE_MANAGER_ALLOCATION> allocationGroup = null;

        foreach (var ag in allocation)
        {
            allocationGroup = ag.Select(a => a);
            var allocationList = allocationGroup.ToList();
            count = allocationList.Count();

            using (ExcelRange Rng = wsSheet1.Cells["A" + startposition + ":G" + (count + previouscount + 1)])
            {
                ExcelTableCollection tblcollection = wsSheet1.Tables;
                ExcelTable table = tblcollection.Add(Rng, "tblAllocations" + count);

                //Set Columns position & name  
                table.Columns[0].Name = "Manager Strategy";
                table.Columns[1].Name = "Fund";
                table.Columns[2].Name = "Portfolio";
                table.Columns[3].Name = "As Of";
                table.Columns[4].Name = "EMV (USD)";
                table.Columns[5].Name = "Percent";
                table.Columns[6].Name = "Allocations";

                wsSheet1.Column(1).Width = 45;
                wsSheet1.Column(2).Width = 45;
                wsSheet1.Column(3).Width = 55;
                wsSheet1.Column(4).Width = 15;
                wsSheet1.Column(5).Width = 25;
                wsSheet1.Column(6).Width = 20;
                wsSheet1.Column(7).Width = 20;

                // table.ShowHeader = true;
                table.ShowFilter = true;
                table.ShowTotal = true;
                //Add TotalsRowFormula into Excel table Columns  
                table.Columns[0].TotalsRowLabel = "Total Rows";
                table.Columns[4].TotalsRowFormula = "SUBTOTAL(109,[EMV (USD)])";
                table.Columns[5].TotalsRowFormula = "SUBTOTAL(109,[Percent])";
                table.Columns[6].TotalsRowFormula = "SUBTOTAL(109,Allocations])";

                table.TableStyle = TableStyles.Dark10;
            }

            foreach (var ac in allocationGroup)
            {
                wsSheet1.Cells["A" + position].Value = ac.MANAGER_STRATEGY_NAME;
                wsSheet1.Cells["B" + position].Value = ac.MANAGER_FUND_NAME;
                wsSheet1.Cells["C" + position].Value = ac.PRODUCT_NAME;
                wsSheet1.Cells["D" + position].Value = ac.EVAL_DATE.ToString("dd MMM, yyyy");
                wsSheet1.Cells["E" + position].Value = ac.UsdEmv;
                wsSheet1.Cells["F" + position].Value = Math.Round(ac.GroupPercent,2);
                wsSheet1.Cells["G" + position].Value = Math.Round(ac.WEIGHT_WITH_EQ,2);
                position++;
            }
            position++;
            previouscount = position;
            // position = position + 1;
            startposition = position;
            position++;
        }
    }
}

This is how the data looks when it is displayed successfully

enter image description here

like image 939
Tom Avatar asked Mar 08 '19 12:03

Tom


1 Answers

Your issue is entirely in your Print method. You've been bitten by creating a slightly over-complicated row tracking mechanism and combining that with magic numbers. This causes you to position each table after the first one row higher than it should be. The header and subtotals are not part of the table, so you have a couple rows of leeway for the error. Tables can't overlap as you've seen, so EPPlus starts barking at you after you've exhausted your leeway.

All you need to do is keep track of the current row that you are writing to, and account for the space taken by your table header and footer (the subtotals) if you use them.

You declare these:

int count = 0;
int previouscount = 0;
var position = 2;
int startposition = 1;

But to write to the correct row, all you need is this:

var rowNumber = 1;

This will properly start writing your data in row one of the Excel sheet. As you write your table rows, you'll track and increment only the rowNumber. But what about the header and footer of each table? If you start writing at the first row of your table you'll overwrite the header, and if you don't account for both the header and footer you'll start having collisions like you've seen. So lets do this:

var showFilter = true;
var showHeader = true;
var showTotals = true;
var rowAdderForHeader = Convert.ToInt32(showHeader);
var rowAdderForFooter = Convert.ToInt32(showTotals);

These are pretty self explanatory, you'll use the rowAdders to hop the header or footer when needed. rowNumber will always be your current row to create your table and write your data. You use the count when defining your table, but we've made it irrelevant for anything else, so we move it:

var allocationList = allocationGroup.ToList();

//Moved here
var count = allocationList.Count();

Your using statement becomes:

using (ExcelRange Rng = wsSheet1.Cells["A" + rowNumber + ":G" + (count + rowNumber)])

Next, it isn't mentioned in your post, but you are going to run into a problem with the following:

ExcelTableCollection tblcollection = wsSheet1.Tables;
ExcelTable table = tblcollection.Add(Rng, "tblAllocations" + count);

Your table names have to be unique, but you could very well wind up with multiple allocations having the same count, which will cause EPPlus to throw an exception at you for duplicating a table name. So you'll want to also track the index of your current table:

var rowNumber = 1;
var tableIndex = 0;

//...
foreach (var ag in allocation)
{
    tableIndex += 1;
    //...
}

And use it to ensure unique table names:

ExcelTableCollection tblcollection = wsSheet1.Tables;
ExcelTable table = tblcollection.Add(Rng, "tblAllocations" + tableIndex);

We use our format control variables:

// table.ShowHeader = true;
table.ShowFilter = true;
table.ShowTotal = true;

//Changes to
table.ShowHeader = showHeader;
table.ShowFilter = showFilter;
table.ShowTotal = showTotals;

You have a small typo here:

table.Columns[6].TotalsRowFormula = "SUBTOTAL(109,Allocations])";

//Should be:
table.Columns[6].TotalsRowFormula = "SUBTOTAL(109,[Allocations])";

After you are done defining your table, you begin writing your data with a foreach loop. In order to prevent overwriting the table header if it exists, we'll have to advance one row. We also have to advance one row for each FIRMWIDE_MANAGER_ALLOCATION. If you are using the subtotals, we have to advance one row after the loop completes in order to properly position the next table:

rowNumber += rowAdderForHeader; 
foreach (var ac in allocationGroup)
{
    //...
    rowNumber += 1;
}
rowNumber += rowAdderForFooter;

And that's it. We now properly track our position using just one variable, and we modify the position as necessary if there is a header or footer on your table.

The following is a complete working example that can be run in LinqPad as long as you add the EPPlus package through Nuget. It creates a random number of allocation groups each with a random number of allocations, and then exports them. Change the output file path to something that works for you:

void Main()
{
    var dataGenerator = new DataGenerator();
    var allocations = dataGenerator.Generate();
    var xlFile = new FileInfo(@"d:\so-test.xlsx");

    if (xlFile.Exists)
    {
        xlFile.Delete();
    }

    using(var xl = new ExcelPackage(xlFile))
    {
        FundAllocationsPrinter.Print(xl, allocations);
        xl.Save();
    }
}

// Define other methods and classes here

public static class FundAllocationsPrinter
{
    public static void Print(ExcelPackage package, ILookup<string, FIRMWIDE_MANAGER_ALLOCATION> allocation)
    {
        ExcelWorksheet wsSheet1 = package.Workbook.Worksheets.Add("Sheet1");
        wsSheet1.Protection.IsProtected = false;

        IEnumerable<FIRMWIDE_MANAGER_ALLOCATION> allocationGroup = null;

        var rowNumber = 1;
        int tableIndex = 0;

        var showFilter = true;
        var showHeader = true;
        var showTotals = true;
        var rowAdderForHeader = Convert.ToInt32(showHeader);
        var rowAdderForFooter = Convert.ToInt32(showTotals);

        foreach (var ag in allocation)
        {
            tableIndex += 1;
            Console.WriteLine(tableIndex);

            allocationGroup = ag.Select(a => a);
            var allocationList = allocationGroup.ToList();
            var count = allocationList.Count();

            using (ExcelRange Rng = wsSheet1.Cells["A" + rowNumber + ":G" + (count + rowNumber)])
            {
                ExcelTableCollection tblcollection = wsSheet1.Tables;
                ExcelTable table = tblcollection.Add(Rng, "tblAllocations" + tableIndex);

                //Set Columns position & name  
                table.Columns[0].Name = "Manager Strategy";
                table.Columns[1].Name = "Fund";
                table.Columns[2].Name = "Portfolio";
                table.Columns[3].Name = "As Of";
                table.Columns[4].Name = "EMV (USD)";
                table.Columns[5].Name = "Percent";
                table.Columns[6].Name = "Allocations";

                wsSheet1.Column(1).Width = 45;
                wsSheet1.Column(2).Width = 45;
                wsSheet1.Column(3).Width = 55;
                wsSheet1.Column(4).Width = 15;
                wsSheet1.Column(5).Width = 25;
                wsSheet1.Column(6).Width = 20;
                wsSheet1.Column(7).Width = 20;

                table.ShowHeader = showHeader;
                table.ShowFilter = showFilter;
                table.ShowTotal = showTotals;
                //Add TotalsRowFormula into Excel table Columns  
                table.Columns[0].TotalsRowLabel = "Total Rows";
                table.Columns[4].TotalsRowFormula = "SUBTOTAL(109,[EMV (USD)])";
                table.Columns[5].TotalsRowFormula = "SUBTOTAL(109,[Percent])";
                table.Columns[6].TotalsRowFormula = "SUBTOTAL(109, [Allocations])";

                table.TableStyle = TableStyles.Dark10;
            }

            //Account for the table header
            rowNumber += rowAdderForHeader; 

            foreach (var ac in allocationGroup)
            {
                wsSheet1.Cells["A" + rowNumber].Value = ac.MANAGER_STRATEGY_NAME;
                wsSheet1.Cells["B" + rowNumber].Value = ac.MANAGER_FUND_NAME;
                wsSheet1.Cells["C" + rowNumber].Value = ac.PRODUCT_NAME;
                wsSheet1.Cells["D" + rowNumber].Value = ac.EVAL_DATE.ToString("dd MMM, yyyy");
                wsSheet1.Cells["E" + rowNumber].Value = ac.UsdEmv;
                wsSheet1.Cells["F" + rowNumber].Value = Math.Round(ac.GroupPercent, 2);
                wsSheet1.Cells["G" + rowNumber].Value = Math.Round(ac.WEIGHT_WITH_EQ, 2);
                rowNumber++;
            }
            //Account for the table footer
            rowNumber += rowAdderForFooter;
        }
    }
}

public class FIRMWIDE_MANAGER_ALLOCATION
{
    public FIRMWIDE_MANAGER_ALLOCATION(string name, Random rnd)
    {
        Name = name;
        MANAGER_STRATEGY_NAME = "strategy name";
        MANAGER_FUND_NAME = "fund name";
        PRODUCT_NAME = "product name";
        EVAL_DATE = DateTime.Now;
        UsdEmv = (decimal)rnd.NextDouble() * 100000000;
        GroupPercent = (decimal)rnd.NextDouble() * 100;
        WEIGHT_WITH_EQ = 0;
    }

    public string Name { get; set; }
    public string MANAGER_STRATEGY_NAME { get; set; }
    public string MANAGER_FUND_NAME { get; set; }
    public string PRODUCT_NAME { get; set; }
    public DateTime EVAL_DATE { get; set; }
    public decimal UsdEmv { get; set; }
    public decimal GroupPercent { get; set; }
    public decimal WEIGHT_WITH_EQ { get; set; }
}

public class DataGenerator
{
    public static Random rnd = new Random();

    public ILookup<string, FIRMWIDE_MANAGER_ALLOCATION> Generate()
    {
        var data = new List<FIRMWIDE_MANAGER_ALLOCATION>();
        var itemCount = rnd.Next(1, 100);

        for (var itemIndex = 0; itemIndex < itemCount; itemIndex++)
        {
            var name = Path.GetRandomFileName();
            data.AddRange(GenerateItems(name));
        }
        return data.ToLookup(d => d.Name, d => d); 
    }

    private IEnumerable<FIRMWIDE_MANAGER_ALLOCATION> GenerateItems(string name)
    {
        var itemCount = rnd.Next(1,100);
        var items = new List<FIRMWIDE_MANAGER_ALLOCATION>();

        for (var itemIndex = 0; itemIndex < itemCount; itemIndex++)
        {
            items.Add(new FIRMWIDE_MANAGER_ALLOCATION(name, rnd));
        }
        return items;
    }
}
like image 55
Dimitri Avatar answered Nov 12 '22 11:11

Dimitri