Invert rows and columns in an Excel file Annother little excercise with openpyxl:

Say you have a Excel file like this:



The Goal is to make make it look like this:



My code to acomplish this:

 inversion.py 

"""
Inverts the content of table row and columns
"""

from copy import copy
import openpyxl
from openpyxl.utils import get_column_letter

def save_workbook_excel_file(workbook, filename: str):
    """Tries to save created data to excel file"""
    try:
        workbook.save(filename)
    except PermissionError:
        print("Error: No permission to save file.")


def invert_row_column(filename: str):
    """
    Main loop to invert rows and column
    """
    workbook = openpyxl.load_workbook(filename)
    sheet_names = workbook.sheetnames
    sheet = workbook[sheet_names[0]]
    workbook.create_sheet(index=0, title='tmp_sheet')
    tmp_sheet = workbook['tmp_sheet']

    data = []
    for row in sheet:
        cells = []
        for cell in row:
            cells.append(cell)
        data.append(cells)

    for x in range(0, len(data)):
        for y in range(0, len(data[x])):
            column = get_column_letter(x + 1)
            row = str(y + 1)
            tmp_sheet[column + row] = copy(data[x][y].value)

    sheet_name = sheet.title
    del workbook[sheet_name]
    tmp_sheet.title = sheet_name
    save_workbook_excel_file(workbook, 'updated_' + filename)


invert_row_column("test.xlsx")


I wonder how this can be improved?
Can the naming be better?
Is there a better / or shorter solution?
Another way to solve this, without using openpyxl and thereby slightly defeating the purpose of learning more about that, would be to use pandas, where this is quite short:

import pandas as pd

# This would load the first sheet by default, but we need the name to save it again
# df = pd.read_excel(filename)  

sheets = pd.read_excel(file_name, sheet_name=None)  # all sheets
sheet_name, df = next(iter(sheets.items()))         # first sheet
df = df.T                                           # transpose
df.to_excel(file_name, sheet_name)                  # write back


This uses pandas.read_excel to read the file and pandas.DataFrame.to_excel to write it back. You need to have the xlrd module installed for this to work.

Feel free to wrap it in functions again if needed.

This should be faster than the manual iteration in Python, since the transpose should happen at C speed.