As an academic administrator, I have to prepare 70 empty grade report spreadsheets templates at the end of each academic quarter: one for each of my teachers. Each copy of the template sheet needs to be named with the teacher’s name and class number. Then the quarter, title and year is appended to the end. For example:
Stephen Hawking 404-23 Q3 Grades 2017.xlsx
The hard way would be to copy and paste a file click the file and rename it, repeating the process 70 error-prone and mind wastingly dull times. I could also get the teachers to rename the file, but…they are teachers, not administrators so…yeah…errors again.
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.
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.