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

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


 

 

[sourcecode language=”python”]

#USAGE python sheetinverter.py <WB>

import logging, openpyxl, os,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 <WB>")
raise;<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>

[/sourcecode]

*Pats back*