Copy 1 column from 100 different Excel paths to 1 Excel file using XL wings

Question:

wb=xw.Book()
for i in ripPaths:   
     wbtemp=xw.Book(i)
     my_values=wbtemp.sheets['sheet1'].range('B5:B4722').options(ndim=2).value
     wb.sheets['sheet1'].range("A1:A4722").value=my_values

I am trying to open 100 excel files I have on my disk successively using the for loop, and then copy the same column from each and paste it into another excel file. The problem is that I keep overwriting ColumnA. I need the A1:A4722 in line 5 to increment to B, C, D, through excel column names.
I’m stuck in the mud!

The goal is to take my 100 excel docs with 1 column each to make a new excel file with 100 excel columns. Thanks for any tips.

Answers:

Sure, here’s my take on it. Letters for this type of thing would be complex since Excel can loop from A-Z and then AA-AZ, etc, however: here’s a method:

wb=xw.Book()
for i in range(len(ripPaths)):   
     wbtemp=xw.Book(ripPaths[i])
     my_values=wbtemp.sheets['sheet1'].range('B5:B4722').options(ndim=2).value
     if i < 26:
        wb.sheets['sheet1'].range(f"{chr(65+i)}1:{chr(65+i)}4722").value=my_values
     elif i < 52:
        wb.sheets['sheet1'].range(f"A{chr(39+i)}1:A{chr(39+i)}4722").value=my_values
     elif i < 78:
        wb.sheets['sheet1'].range(f"B{chr(13+i)}1:B{chr(13+i)}4722").value=my_values
     elif i < 104:
        wb.sheets['sheet1'].range(f"C{chr(-13+i)}1:C{chr(-13+i)}4722").value=my_values

This uses f-strings, you can use another form of string formatting if you so choose.

Answered By: Aditya Diwakar
wb=xw.Book()
for i in range(3):   
     wbtemp=xw.Book(ripPaths[i])
   my_values=wbtemp.sheets['sheet1'].range('B5:B4722').options(ndim=2).value
     wb.sheets.active.range((1,i+1)).value=my_values

Aditya’s answer with f strings is sick, but this is smoother. Thanks for the tip, Felix.

Answered By: Rudolf the Reindeer
dst_wb = xw.Book()
sh = wb.sheets['sheet1']
for i, path in enumerate(ripPaths):   
     scr_wb = xw.Book(path)
     src_sh = scr_wb.sheets['sheet1']
     values = src_sh['B5:B4722'].options(ndim=2).value
     sh[0,i].value= values
Answered By: Pranay
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.