简体   繁体   中英

Openpyxl - How to copy data range from an excel worksheet to another

I'm trying to copy a range of data based on row coordinates from a sheet to another.

I have a list with row coordinates tbrow = [1, 34, 52, 75, 101]

What I would like to do is to copy the row range from:

1 to 34 from sheet 0 to sheet 1,

34 to 52 from sheet 0 to sheet 2,

52 to 75 from sheet 0 to sheet 3,

75 to 101 from sheet 0 to sheet 4.

What I tried so far is the following:

-Get the main sheet 0

sheet0 = wb["Sheet"]

Then I stored the sheets in a variable, ignoring the first sheet

sheets = wb.worksheets[1:]

In the end, I tried to copy the given values.

for i in range(tbrow[i],tbrow[i]+1) for j in range(1,sheet0.max_column+1): for k in sheets: k.cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value

Problem is that I get only the first row copied to the rest of the sheets and not the whole range. (1-34;34-52 and so on) What am I missing?

Can anyone help me on organizing a logic in here? Or provide a solution?

Thank you!

UPDATE

Another approach was to slice the list.

a,b = tbrow[:2] for i in range(a,b): for j in range(1,sheet1.max_column+1): for k in sheets: k.cell(row=i, column=j).value = sheet1.cell(row=i, column=j).value

But that takes only the first two row coordinates from the list and I would like to go to the next item in the list:

-From first to second

-From second to third

-From third to fourth

...and so on –

The problem I notice with your code is the value of i inside the range method. The i inside the range method is not the same as the i being used in the for loop. I am assuming you must have a global definition of i=0 which is then not updated, hence why only the first rows are copied to the next sheet.

for i in range(tbrow[i],tbrow[i]+1):#------here
    for j in range(1,sheet0.max_column+1):
        for k in sheets:
            k.cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value

Consider using a function where u can the pass the values of the rows

def addRowsToSheet(lb,ub):
    for i in range(lb,ub):#------here
        for j in range(1,sheet0.max_column+1):
              #consider using switch case, instad of the loop
              switch (ub):
                  case 34:
                    sheets[0].cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value;
                    sheets[1].cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value;
                  case 52:
                    sheets[2].cell(row=i, column=j).value = sheet0.cell(row=i, column=j).value;

              #Do the same logic below

#calls
for i in range(0,len(tbrow)-1):
     addRowsToSheet(tbrow[i],tbrow[i+1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM