Coding

Python Learning: Automate Boring Stuff with Python | Chapter 12: Spreadsheet to Text Files

Chapter 12 done!!! Finally

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


Suggestions are welcomed.

#USAGE python sheet2text.py <EXCELFILE>


import logging, sys, os, 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 = ""
			newFile.write( data )
		newFile.close
	wb.close()
else:
	logging.error("USAGE python sheet2text.py <EXCELFILE>")<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>

Excited over the next chapter..see ya!

error: Content is protected !!