Search code examples
excelpython-3.xxlwings

Xlwings - adding columns


I am using xlwings and am trying to sum two cells, A1 + B1, and have the output entered into a third cell C1. I want to to do this for a range (A1->A9) + (B1->B9) and have them written to cells (C1->C9). My current command is Range('C3').value = [sum(x) for x in zip(Range('A3:A9').value, Range('B3:B9').value)] This sums the values correctly but the answers are written out horizontally to cells C3-I3. I know that the command Range('A1').value = [[1],[2],[3],[4],[5]] would list the elements of a list vertically but I am not sure how to incorporate this into my command.

Any help would be appreciated


Solution

  • Making this easier is an open issue. For simple lists, you can do the following (note that on Python 2, you don't need list around zip:

    Range('C3').value = list(zip([sum(x) for x in zip(Range('A3:A9').value,
                                  Range('B3:B9').value)]))
    

    If you have numpy installed, the same can be achieved like that:

    import numpy as np
    Range('C3').value = (Range('A3:A9', asarray=True).value + 
                         Range('B3:B9', asarray=True).value)[:,np.newaxis]