Python Learning: Automate Boring Stuff with Python | Chapter 12: Spreadsheet cell Inverter 2020

This isn’t too bad …right ?

Not too tired but would rather be sleeping now. Unfortunately I have to finish this chapter before Sunday.. sighs deeply 2:53:05 AM


 

 

# USAGE python sheetinverter.py 

import logging
import openpyxl
import os
import sys

logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s - %(levelname)s - %(message)s")

if len(sys.argv) == 2:
    # TODO: EXTRACT WB
    wb = sys.argv[1]
    wb = os.path.abspath(wb)
    try:
        workbook = openpyxl.load_workbook(wb)
        # TODO: GET ACTIVE SHEET
        active = workbook.get_active_sheet()
        if not active:
            logging.error("Excel Workbook should have at least a sheet")
            raise
        if active.max_row <= 0 or active.max_column <= 0:
            logging.error("Excel Workbook should have a sheet with data")
            raise
        # TODO: CREATE NEW SHEET
        # TODO: RE-NAME THE NEW SHEET
        invert = workbook.create_sheet("Inverted")
        # TODO: LOOP THROUGH ACTIVE SHEET AND UPDATE NEW SHEET
        for row in range(1, active.max_row):
            for col in range(1, active.max_column):
                invert.cell(row=col, column=row).value = active.cell(
                    row=row, column=col).value
        workbook.save(wb)
        workbook.close()
    except Exception as err:
        logging.error("Error at opening workbook: " + str(err))
else:
    logging.error("USAGE python sheetinverter.py ")

*Pats back*