Copy and paste ranges in excel with OpenPyXl and Python 3

OpenPyXl is a Python open library that allows you to read and write Microsoft Excel files. Specifically, the ‘*.xlsx’ file extension. It helps you to create programs to create and modify files and automate your processes in excel.

Python Logo

NOTE: This post requires that you have some knowledge of Python and the OpenPyXl library. The library also needs to be installed for you to use. 

Quite often, I find that I have to work with ranges of data that I need to either copy and paste into a new file or files, or copy > modify > paste into files.

The OpenPyXl library allows you to look at every cell of a file and either copy it or modify it by using the openpyxl.worksheet.Worksheet.cell() method. This method allows you to access each cell by the row and column as a numerical value. 

Note! Unlike everything else in coding, rows and columns start with one(1) and not zero(0).

To select whole ranges of our data we need to iterate through it by both row and column and then store that data in a list to be pasted to the new file, spreadsheet or location that we desire.

The following example will take you through the process. For your own data you will need to modify the file, sheet and range locations. Everything else should be good to go.

You can find the whole code at the end of the post.

Why does your MS Excel look weird?

To be honest my screenshots of the ‘.xlsx files will be in Libreoffice. But this simple example will be able to load without issue in MS Excel.

The Example

Source Data

The source data for this example is a very simplified version of grade data that I work with day-to-day. The goal of our program is to simply copy the Section 12  results into a new file. The file for this spreadsheet is called: GradeSample.xlsx. I have put it in the same folder as my Python program.

Sample Data

Receiving File

For the purpose of this example, we have a file that we want to save this data into: Section12Grades.xlsx. We could just as easily use a template and save the file under a different name – for example, template.xlsx could save as sec12Grade.xlsx. This could be useful if I wanted to save a file for each section.

The receiving file looks like this:

receiving File

 

Loading the Source Data and Receiving File

Okay, let’s get started with the program. First, we need to load both the source data and the receiving file.

We import he OpenPyXl library first.

Next, we’ll open the source data with wb = openpyxl.load_workbook("GradeSample.xlsx") . Once we have loaded the workbook we need to tell Python which sheet tab we want it to work in. We do this by calling the workbook (wb) and then get the sheet by its name: sheet = wb.get_sheet_by_name("Grades")

We repeat this step with the receiving data file that we want to paste our Section 12 grades into.

Copying the Section 12 data

Looking at the section 12 data, we want Python to be able to copy from column A2 to D14. the OpenPyXl .cell() method takes a number which is much easier to iterate, rather than the column letters. So let’s look at that range again:

  • From: A2 is now column = 1 and row = 2
  • To: D14 in now column = 4 and row = 14

Once we access this data, we need somewhere to store it before we paste it into the new file. We will use a nested list for this.

In line 3 we create our function copyRange. It contains 5 arguments that we could add with our information as follows:

  • startCol = 1
  • startRow = 2
  • endCol = 4
  • endRow = 14
  • sheet = sheet ( The name of the sheet variable we are copying the data from which is GradeSample.xlsxsheet Grades)

In line 4 we create an empty list called rangeSelected this list will have data from every row we have selected.

Line 5 starts the for loop through each row. Each row contains data in each column so we create an empty list (rowSelected) here in preparation to add the column data to in the next for loop (Line 6).

Line 6 loops through each item in each column of the selected row. Line 7 then adds the data from each column to the rowSelected lists.

Once it finishes this loop, it adds the data from the rowSelected lists into the rangeSelected lists. It then moves down to the next row and repeats the process continuing through the rows until the loop meets its end at row 14.

Finally the copyRange function returns the rangeSelected list to be used at our discretion.

Pasting the selected data

Now we have a nested list of all the rows and the information in the columns we require from those rows.

We will use that list add it to our Section12Grades.xlsx in Sheet1.

We want to add the data starting at row 3 this time because we have a title on row 1 and column headers on row 2.

We will be up for two more for loops to do this.

Let’s take a look:

Line 3 starts our pasteRange function and contains the following arguments:

  • startCol = 1
  • startRow = 3 (because we want to paste the data 1 row down.)
  • endCol =  4
  • endRow = 15 (because we want to paste the data 1 row down.)
  • sheetReceiving = temp_sheet (This is the variable for Section12Grades.xlsx with the sheet name, Sheet1.
  • copiedData = rangeSelected ( The returned list from your copyRange function)

Line 5 creates a count number variable starting with zero(0) so we can start looking through our copiedData lists by rows from the beginning.

Line 6 begins the row loop like the copyRange function.

Line 7 adds another count number variable so we can loop through our copiedData list by columns.

Line 8 begins the column loop.

Line 9 adds the copiedData cell-by-cell to the new file. It does not save it here but holds it in memory to be saved to the file we choose in the future.

Finally, we add 1 to each of the counters so we can move onto the next cell.

Running a Copy and Paste as a function

We are now going to create a function to copy the data using the copyRange function and paste the data using the pasteRange function and then we will save the Section12Grades.xlsx file contained in the variable, template.

This is how it will look:

Line 1 creates the function and then line 3 runs the copyRange process with the arguments we need.

Note! After line 3 you could call a function to manipulate the data or add styling here before you paste it.

Line 4 then runs the pasteRange function with the arguments we need.

Line 5 then saves the pasted data in the same file that we used in our memory. You could equally save the file with a different name and this will create a brand new file with the pasted data in it.

That’s it! Done.

Run the program

Now it’s time to run the program. Save the file and hit run (F5).

In the Python Shell run the program and then enter:

Your result will look like this:

Not too impressive, right?

Go into the folder and open your Section12Grades.xlsx spreadsheet.

It should now look like this:

End Result of openpyxl copy and paste range

The full OpenPyXl copy and paste range code

 

Edit: 18 Nov 2018

From OpenPyXl version 2.5 onward, you might find that you get a Depreciation warning for:

  •  sheet = wb.get_sheet_by_name("foo") #Add Sheet name
  • temp_sheet = template.get_sheet_by_name("foo2") #Add Sheet name

OpenPyXl 2.5 now provides the sheet names in a convenient list:

  • sheet = wb["foo"]#Add Sheet name
  • temp_sheet = template["foo2"]#Add Sheet name

Her is the updated code:

Big thanks to WY in the comments for reminding me to update this.

Want to learn how to automate your daily admin at work with Python? Udemy has some great Python automation courses that will help you learn how to automate your tasks so you can focus on what really matters.

 

Got a more specific problem you need help with, but don’t have the time to develop the skills? Fiverr’s your best bet to find a skilled professional to solve your problem quickly and cheaply. *

 

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

 

59 thoughts on “Copy and paste ranges in excel with OpenPyXl and Python 3”

  1. This is very useful. As I tried your codes I encounter an issue with latest openpyxl.
    The error is
    sheet = wb.get_sheet_by_name(“Grades”) #Add Sheet name
    DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]).

    But a simple fix in your orginal code (just two lines) as
    sheet = wb[“Grades”]
    temp_sheet = template[“Sheet1”]
    will solve all issue. I guess it will be useful to others beginner as I am.

    1. Hi WY,
      Thanks for the reminder. I noticed this change too when working on a project last week, but didn’t get around to updating the post. I’ve added an update to the bottom of the post for now just in case folks are still using an older version and then down the track I will redo the relevant parts of the post. Much appreciated.

      1. Hey mate,

        Thanks for this. However after using the copyrange function and having a look at the output range selected it appears to display only the last row and none of the preceeding rows have been added to the rangeselected object. Any idea why that would happen?

        1. Hi Kunal,

          The rowSelected needs to clear after it is appended to rangeSelected variable so it can, on the next iteration, start afresh with the following row.

          Hope this makes sense.

  2. Hi Yagi,

    This article is extremely helpful as I’ve been trying to copy columns from one spreadsheet into another template with formulas using xlrd and xlwt with no avail.

    I’m using PyCharm. I’ve replaced your filenames and sheets with my filenames and sheets. It’s not throwing any errors. However I am unable to write to a new file. What is interesting is that in your line 46:
    pastingRange = pasteRange(1, 3, 4, 15, temp_sheet, selectedRange) # Change the 4 number values

    “pastingRange” is showing as commented out, even though it is not. The variable range does not return anything and no file is saved.

    Anyone experience this or have any insight?
    Please let me know…….tnx!

      1. Yagi,

        Actually, I just removed line 43 and it works w/o being a function. I think it just works better this way for what I’m doing. Anyway, thanks for this. It’s a huge help!!

        JJ

  3. Thanks for the excellent example but it is very much a programmers perspective rather than a users perspective. A more natural approach would be cell references of A3:D15, copy range, set an active cell in the destination and then just paste the range at the destination active cell.

    1. Yep very useful, anon. Though if the data is being manipulated between copy and paste then I’m not sure that is the best approach.

  4. Should not need to specify endCol and endRow because it can be calculated from rangeSelected.

    1. That depends if the user wants to paste everything they copied or just part of it. That’s probably why they retain this functionality in VB and Google Apps Script.

  5. hey you are great!
    i want to ask a question….what if we want to paste the copied data in a website at a specific location.

    1. Hi Akhilesh, I guess you could save the data as a text file or csv and create a table with html and Javascript then call the data in the file. Alternatively, studying up on Pandas or a similar library might be useful too. Good luck.

  6. Hey Yagi!

    I’m having some trouble with your code. It’s not letting me open the updated file. The error I’m getting is excel cannot open the file format or file extension. I’m using Python 3.7, openpyxl 3.5.5, and Pycharm. I’ve tried to write code to work around this but I keep having trouble.

    Your code is great though! It is clear and easy to read and applicable across a wide variety of situations.

    Thanks!

    1. Hi Caitlynne,
      I’m uncertain what could cause the error without seeing the code. You could try and replicate a successful operation on a simpler version of your project and then scale up.

  7. Hey Yagi

    Thank you for the code it is really useful for my work, i have a question if you don’t mind, how can tell the paste function to paste the whole data after the that is there in the sheet ? for example there is a sheet with data in it i want to paste the new data after the old data that is there.

    Another problem is i have some graphs in my template file that i want to paste the data into, after i paste the data the graphs are gone. Why is that ?

    Thank you.

  8. For those who need a code thats simplified that just copys and pastes

    def copypaste(startCol, startRow, endCol, endRow, copying_sheet, pasting_sheet):
    rangeSelected = []
    #Loops through selected Rows
    for i in range(startRow,endRow + 1,1):
    #Appends the row to a RowSelected list
    rowSelected = []
    for j in range(startCol,endCol+1,1):
    rowSelected.append(copying_sheet.cell(row = i, column = j).value)
    #Adds the RowSelected List and nests inside the rangeSelected
    rangeSelected.append(rowSelected)

    countRow = 0
    for i in range(startRow,endRow+1,1):
    countCol = 0
    for j in range(startCol,endCol+1,1):
    pasting_sheet.cell(row = i, column = j).value = rangeSeleted[countRow][countCol]
    countCol += 1
    countRow += 1

    #EDIT: I removed the return rangeSelected as you mentioned. ~Yagi

    1. Nice work, Jonathan! For users, just remember the paste location on the new sheet will be identical to the origin sheet.

  9. Great routine! Just what I was looking for! I am just a beginner at Python. I tried it in the idle3 shell to try and understand what was happening. I still don’t quite get: selectedRange in pastingRange = pasteRange(1,3,4,15,temp_sheet,selectedRange) Why isn’t that rangeSelected??

    I would like to modify it to enter the start and finish rows and columns by hand, to make it very flexible. Where is the best place to put that? I think, at the beginning of createData(). Something like:

    copyBeginRow = input()
    copyBeginColumn = input()
    copyEndRow = input()
    copyEndColumn = input()

    Then hand them to

    selectedRange = copyRange(copyBeginColumn,copyBeginRow,copyEndColumn,copyEndRow,sheet)

    and the same for pasteRange(pasteBeginColumn,pasteBeginRow,pasteEndColumn,pasteEndRow,temp_sheet,selectedRange)

    Mostly, I need to go to wb.active.max_row but the columns I need are not always the same, because each week I need to first insert 3 new columns. So maybe I just need to enter beginColumn and endColumn.

    Also, is it possible to copy formulas over? I need these in the columns 4,5,6 & 7.

  10. On Python 3.7.0, I keep getting an “NameError: name ‘rangeSelected’ is not defined” on the def pasteRange row (copiedData=rangeSelected).

    Is anyone else getting this error?

  11. Nice article!
    I tried to run your code but got this invalid syntax message

    File “”, line 3
    def copyRange(1, 2, 4, 14, sheet):
    ^
    SyntaxError: invalid syntax

    The code was exactly the one you have written:

    def copyRange(1, 2, 4, 14, sheet):
    rangeSelected = []
    #Loops through selected Rows
    for i in range(2,14 + 1,1):
    #Appends the row to a RowSelected list
    rowSelected = []
    for j in range(1,4+1,1):
    rowSelected.append(sheet.cell(row = i, column = j).value)
    #Adds the RowSelected List and nests inside the rangeSelected
    rangeSelected.append(rowSelected)

    return rangeSelected

    I’m pretty new to python (working on my first project) so there is probably some really rookie mistake, but I can’t find it none the less.

    1. Hi Rasmus,

      Have a look through the part of the tutorial headed: Running a Copy and Paste as a function.

      To copy a range you will need to call the “copyRange” function. So outside the function you could do something like this:
      myDataToCopy = copyRange(1, 2, 4, 14, sheet)

      This will then input those values into the “copyRange” function ==> def copyRange(startCol, startRow, endCol, endRow, sheet):

      Hope this helps.
      ~Yagi

  12. Great article. This explains the step by step procedure with code.
    Very useful for novice users like me.
    I got praise from my manager if office !!!!

  13. The code is working fine, but when try to copy the range in a sheet, which already contains some data, the original data is getting lost and the new data(pasted data) is appearing. How can i fix this ?

    1. Yep. That seems to be performing as expected. If you want to only change certain parts of a range, you will have to update cell by cell.

  14. Is there a way to copy only visible cells/rows instead of all the cells specified in copyrange function?

  15. Thank you for taking the time to put this together! This is very helpful to a noob like me. 🙂

  16. Hi Yaki, Thank you for your work. I just have some problems. What if I want to copy the same column from multiple sheets to one sheet ?

  17. Hi there,
    Thanks for taking the time to post this! it’s definitely very helpful.

    However, I keep receiving the error “NameError: name “selectedRange” is not defined” I then replaced that with rangeSelected (just in case you made an error by switching the words) and copiedData, however they all seem to send me back the same error message.

    I have also made sure to change the sheet-naming syntax to suit the updated openpyxl version.

    If you or anybody has information to fix this error, you’d be helping me heaps!

    Thanks in advance 🙂

    1. Alright nevermind, I just realized I misspelled copiedData (d’oh!!!).
      However, now I’m a little confused with the logic behind that variable.
      I’m confused because it is not exactly defined, and just happened to show up when you were defining the pasteRange.
      Alright, now that I’ve written that sentence, I realized that the def function could have defined the whole row of:
      (startCol, startRow, endCol, endRow, mastersheet,copiedData).

      Please correct me if i’m wrong (i’m still in the process of learning Python and i’m conducting my first automation project right now), but is what i assume about the def function correct? As in Python you may not always need to define a variable before you use it (but as you can see, this can be pretty confusing for a noobie!!).

      Cheers,
      RH

  18. I have been using your function and it works great ! Thanks.

    I only encounter a small problem. When I try to paste data in a large xlsx template, i get the :

    sheetReceiving.cell(row=i, column=j).value = copiedData[countRow][countCol]
    IndexError : List index out of range.

    The template is created via Python and has 30 columns. Trying to paste data in cols 6-8 from a workbook with only 4 rows and it does not like it.

    Any idea?

    Thanks,

    Max

  19. Hi,

    I am able to run this with no errors on my pc, but on a mac I am getting AttributeError: ‘MergedCell’ object has no attribute ‘value’ – any ideas how to fix this?

    1. Hi Philipp,

      I am not 100% certain. My guess is that it might be due to the difference in file paths.

  20. Hi Yagi,

    This is really helpful, and well organized!

    However, i am encountering an error when using this to copy a block of merged and un-merged cells from the original wb to a template wb in a different directory.

    When the paste_range function is called, i receive an AttributeError: ‘MergedCell’ object attribute ‘value’ is read only.

    Any tips on how to get merged cells to paste?

    1. Hi AJ,

      Thanks for the kind words. Unfortunately, I don’t think you would be able to use this code with merged cells it seems. I and facing the same error. I haven’t visited the OpenPyXl library in quite some time.

      Hopefully, I will have some free time to revisit it soon and see if I can find a way to deal with merged cells.

      ~Yagi

  21. Hi Yagi,

    Can I do the same for xlsm file ?
    I wanna copy data from xlsx file and paste to xlsm file

      1. Unfortunetly it doesn’t work. I have Excel 2016 version and openpyxl module sends me error : Slicer List extension is not supported and will be removed. I tried use xlrd module but it doesn’t work too. Error : sheetReceiving.cell(rowx = i,colx = j).value = copiedData[countRow][countCol]
        File “C:\Python36\lib\site-packages\xlrd\sheet.py”, line 412, in cell
        self._cell_types[rowx][colx],
        IndexError: list index out of range

        Do you know what i should do ?

  22. I have the code down pat and it would be nice if it worked, I keep getting the error “Assigning result of a function call, where the function has no return pylint(assignment-from-no-return)” and “Unused variable ‘pastingRange’ pylint(unused-variable)”, would really like it to work, thanks for any help. Thank you also for making it easier for me to complete my project by having this code make easy sense!

    1. Hi Orion,

      Thanks for the kind words.

      It is difficult to tell without seeing a copy of your code, but how did you apply the pasteRange function that was set to pastingRange? Did you add all 6 variables?

      Cheers,
      Yagi

  23. Hi, Yagi.

    Your code is working great in my application of it. I do have one question, however. Is there a way to have the script paste to multiple sheets in the same workbook after copying the data?

  24. I have tried to run the above code (with a few edits) and I am having some trouble. I am using python 3.7 and pycharm. I am running from terminal.

    The code runs fine but nothing is pasting into the new file. I have also tried including print functions in the def copyRange(), the def pasteRange() and def createData() functions but these are not being printed while the code runs.

    RAW CODE

    import openpyxl

    from openpyxl import load_workbook

    Import_file = ‘Excel_File.xlsx’ # Ensure that the title of the import excel between ” is written exactly as saved.
    Export_file = ‘Book7.xlsx’ # Ensure that the title of the export excel between ” is written exactly as saved.

    wb = load_workbook(‘Excel_File.xlsx’)
    sheet = wb[‘Sheet3’]
    ws = wb.active

    template = load_workbook(‘Book7.xlsx’)
    temp_sheet = template[‘Sheet3’]

    print(sheet, temp_sheet)

    def copyRange(startCol, startRow, endCol, endRow, sheet):
    rangeSelected = []
    for i in range(startRow, endRow + 1, 1):
    rowSelected = []
    for j in range(startCol, endCol + 1, 1):
    rowSelected.append(sheet.cell(row=i, column=j).value)
    rangeSelected.append(rowSelected)

    print(‘copy function created’)

    def pasteRange(startCol, startRow, endCol, endRow, sheetReceiving, copiedData):
    countRow = 0
    for i in range(startRow, endRow + 1, 1):
    countCol = 0
    for j in range(startCol, endCol + 1, 1):
    sheetReceiving.cell(row=i, column=j).value = copiedData[countRow][countCol]
    countCol += 1
    countRow += 1

    print(‘paste function created’)

    def createData():
    print(‘Processing…’)
    selectedRange = copyRange(1, 2, 4, 14, sheet)
    pastingRange = pasteRange(1, 3, 4, 14, temp_sheet, selectedRange)
    template.save(Export_file)

    print(‘data pasted to new file’)

  25. Hi,

    i want my data to be change in the format using python. anyone can help me out with this problem because i was trying this last 1 week but i am not getting the result.

    1) Name in the heading from “A1:O2” with merge and center the text.
    2) Then from “A3:O3” all my headings of the data which i have.
    3) Then in “A4:O4” i want a “text” and beside that count of the data below. and its colour should be green background
    4) Then from “A5” my data starts.
    5) The data should be Autofit in the cell and alignment should be in the middle.

    can anyone help me with this format. Please

  26. Helli after I run the command on my terminal
    python test1.py
    Nothing is happening so I am not sure is it working or not. Can you please help ?

    1. Hi Jaimin,

      It is difficult to determine what the error is with this information. I recommend posting some of your code or trying to replicate the error in a test and posting it and I or someone from the community might be able to guide you better, mate.

      Cheers,
      Yagi

  27. I’ve also tried to modify copyRange and pasteRange functions like you did in your tutorial but it did not work:

    #Copy range of cells as a nested list
    #Takes: start cell, end cell, and sheet you want to copy from.

    def copyRange(startCol, startRow, endCol, endRow, sheet):
    rangeSelected = []
    #Loops through selected Rows
    for i in range(startRow,endRow+1,1):
    #Appends the row to a RowSelected list
    rowSelected = []
    for j in range(startCol, endCol+1,1):
    rowSelected.append(sheet.cell(row = i, column = j).value)
    #Adds the RowSelected List and nests inside the rangeSelected
    rangeSelected.append(rowSelected)

    #Paste range
    #Paste data from copyRange into template sheet
    def pasteRange(startCol, startRow, endCol, endRow, sheetReceiving, copiedData):
    countRow = 0
    for i in range(startRow,endRow+1,1):
    countCol = 0
    for j in range(startCol,endCol+1,1):

    def createData():
    print(“Processing…”)
    selectedRange = copyRange(1,7,ws0End_column,ws0End_row, ws0)
    pastingRange = pasteRange(1,1,ws1End_column,ws1End_row,ws1,selectedRange)
    template.save(“Section12Grades.xlsx”)
    print(“Range copied and pasted!”)

    createData()

    Processing…

    IndexError Traceback (most recent call last)
    in
    —-> 1 createData()

    in createData()
    2 print(“Processing…”)
    3 selectedRange = copyRange(1,7,ws0End_column,ws0End_row, ws0)
    —-> 4 pastingRange = pasteRange(1,1,ws1End_column,ws1End_row,ws1,selectedRange)
    5 template.save(“Section12Grades.xlsx”)
    6 print(“Range copied and pasted!”)

    in pasteRange(startCol, startRow, endCol, endRow, sheetReceiving, copiedData)
    7 for j in range(startCol,endCol+1,1):
    8
    —-> 9 sheetReceiving.cell(row = i, column = j).value = copiedData[countRow][countCol]
    10 countCol += 1
    11 countRow += 1

    IndexError: list index out of range

  28. Its really helped me a lot for my project.

    Can someone suggest me to copy and paste the data in excel templates based on not just cell ranges but based on column and index lables.

Comments are closed.