Search code examples
pythonpython-2.7scriptingexcel-2010datanitro

Concatenation of 3 columns (total number of possible combinations) using DataNitro


I am new to DataNitro and I am also a Python beginner, and currently exploring the endless possibilities of Excel spreadsheet programming using DataNitro.

I would like to concatenate 3 different columns (A, B & C) and would like to generate every possible combination of 3 with them.

   A                      B               C

172-000072-00   523-000072-00   120-000172-01
172-000072-04   523-000072-01   120-000172-06
172-000072-01   523-000072-02   120-000172-07
172-000072-05   523-000072-03   120-000172-08
172-000072-08   523-000072-04   120-000161-01
172-000072-09   523-000072-05   120-000161-06
                523-000072-06   120-000161-07
                523-000072-07   120-000161-08

One combination could be "172-000072-00 / 523-000072-00 / 120-000172-01"

There would be 6 X 8 X 8 = 384 combinations.

How can I generate this in Excel using DataNitro?

I tried to make my own implementation for this problem -

def conctn():
    CellRange("E1:E384").value = 
[for x in CellRange("A1:A5"):
    for y in CellRange("B1:B8"):
        for z in CellRange("C1:C8"):
            return CellRange(z).value

             return CellRange(y).value + CellRange(z).value

     return CellRange(x).value + CellRange(y).value + CellRange(z).value]

Solution

  • This should work:

    to_write = []
    
    for x in CellRange("A1:A5").value:
        for y in CellRange("B1:B8").value:
            for z in CellRange("C1:C8").value:
                to_write.append(' / '.join([x, y, z]))
    
    Cell("E1").vertical = to_write
    

    Here's what's happening here:

    The first line is creating a list you can use to store all the permutations, and the last line is using the 'vertical' keyword to write this list to Excel. This keyword is a shortcut for writing a column starting from a given cell without figuring out how long it is.

    The three 'for' loops iterate through every combination of variables.

    "' / '.join([x, y, z])" takes a list of striings ("[x, y, z]") and joins them into one string, with " / " as the separator.