4

Is there any .net library available to unpivot excel data? I am currently using LinqToExcel framework to read data from spreadsheets, so not sure if there are dynamic linq queries available to perform the unpivot. Thanks for any suggestions. BTW, I am looking for a solution which could handle multiple columns.

Example Original Table

Product Location  Customer1   Customer2   Customer3
  A        X          10         20         100

Destinaton Table

Product Location Customer    Demand
  A        X      Customer1    10
  A        X      Customer2    20
  A        X      Customer3    100
user320587
  • 1,347
  • 7
  • 29
  • 57

1 Answers1

5

Try something like this:

var customer1 =
    from c in excel.Worksheet()
    select new
    {
        Product = c["Product"],
        Location = c["Location"],
        Customer = "Customer1",
        Demand = c["Customer1"],
    };

var customer2 =
    from c in excel.Worksheet()
    select new
    {
        Product = c["Product"],
        Location = c["Location"],
        Customer = "Customer2",
        Demand = c["Customer2"],
    };

var customer3 =
    from c in excel.Worksheet()
    select new
    {
        Product = c["Product"],
        Location = c["Location"],
        Customer = "Customer3",
        Demand = c["Customer3"],
    };

var customers = customer1.Union(customer2).Union(customer3);

Based on your comment try this:

var columns = 4; /* how many columns to unpivot */
var customers =
    from n in Enumerable.Range(2, columns)
    from c in excel.Worksheet()
    select new
    {
        Product = c["Product"].Value,
        Location = c["Location"].Value,
        Column = n.ToString(),
        Demand = c[n].Value,
    };
Enigmativity
  • 113,464
  • 11
  • 89
  • 172