python add data to existing excel cell Win32com

5.5k views Asked by At

Assume I have A1 as the only cell in a workbook, and it's blank. I want my code to add "1" "2" and "3" to it so it says "1 2 3"

As of now I have:

NUMBERS = [1, 2, 3, 4, 5]
ThisSheet.Cells(1,1).Value = NUMBERS

this just writes the first value to the cell. I tried

ThisSheet.Cells(1,1).Value = Numbers[0-2]

but that just puts the LAST value in there. Is there a way for me to just add all of the data in there? This information will always be in String format, and I need to use Win32Com.

update: I did

stringVar = ', '.join(str(v) for v in LIST)

UPDATE:this .join works perfectly for the NUMBERS list. Now I tried attributing it to another list that looks like this

LIST=[Description Good\nBad, Description Valid\nInvalid]

If I print LIST[0] The outcome is

Description Good
Bad

Which is what I want. But if I use .join on this one, it prints

('Description Good\nBad, Description Valid\nInvalid')

so for this one I need it to print as though I did LIST[0] and LIST[1]

1

There are 1 answers

4
otorrillas On BEST ANSWER

So if you want to put each number in a different cell, you would do something like:

it = 1
for num in NUMBERS:
    ThisSheet.Cells(1,it).Value = num
    it += 1

Or if you want the first 3 numbers in the same cell:

ThisSheet.Cells(1,it).Value = ' '.join([str(num) for num in NUMBERS[:3]])

Or all of the elements in NUMBERS:

ThisSheet.Cells(1,1).Value = ' '.join([str(num) for num in NUMBERS])

EDIT

Based on your question edit, for string types containing \n and assuming every time you find a newline character, you want to jump to the next row:

# Split the LIST[0] by the \n character
splitted_lst0 = LIST[0].split('\n')
# Iterate through the LIST[0] splitted by newlines
it = 1
for line in splitted_lst0:
     ThisSheet.Cells(1,it).Value = line
     it += 1

If you want to do this for the whole LIST and not only for LIST[0], first merge it with the join method and split it just after it:

joined_list = (''.join(LIST)).split('\n')

And then, iterate through it the same way as we did before.