Chapter 12 done!!! Finally

Now I can sleep.. for 10 minutes though.. 3:42:14 AM


Suggestions are welcomed.

# USAGE python sheet2text.py 

import logging
import sys
import os
import openpyxl

logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s - %(levelname)s - %(message)s")
if len(sys.argv) == 2:
    # TODO: EXTRACTS EXCEL FILE
    excelfile = sys.argv[1]
    excelfile = os.path.abspath(excelfile)
    excelfile_name = os.path.basename(excelfile).split(".")[0]
    if not os.path.exists(excelfile):
        logging.error("Excel File " + excelfile + " does not exists")
        raise
    # TODO: OPENS FILE
    wb = openpyxl.load_workbook(excelfile)
    # TODO: GET ACTIVE SHEET
    ws = wb.active
    if not ws:
        logging.error("Excel File should have at least a sheet with data")
        raise
    if ws.max_row <= 0 or ws.max_column <= 0:
        logging.error("Excel File should contain data")
        raise
    # TODO: LOOP OVER COLUMNS
    # Each column = a new file; thus
    for col in range(1, ws.max_column + 1):
        # TODO: CREATE NEW TEXT FILES
        newFile = open(excelfile_name + "_column" + str(col) + ".txt", "a")
        # read each row
        for row in range(1, ws.max_row):
            data = ws.cell(column=col, row=row).value
            if not data:
                data = ""
            # ensure all values ( including ints) are strings
            data = str(data) + "\n"
            newFile.write(data)
        newFile.close
    wb.close()
else:
    logging.error("USAGE python sheet2text.py ")

Excited over the next chapter..see ya!

%d bloggers like this: