I am new to python, just getting started with it and I was trying to do some task with python. I have an excel file that I want to automatically check if it meets the criteria that I want to set.
There’s a module called “openpyxl” which can read Excel spreadsheets.
Install with “pip install openpyxl”. The module is here:
https://pypi.org/project/openpyxl/
and the docs here:
https://openpyxl.readthedocs.io/en/latest/
Cheers,
Cameron Simpson cs@cskk.id.au
I wrote this for a colleague who is just starting to learn python. It might be a useful example.
import sys
import openpyxl
from openpyxl import load_workbook
# the following will suppress any warnings
import warnings
warnings.filterwarnings("ignore")
def main(infile):
print("starting main: file = " + str(infile))
try:
wb = load_workbook(infile)
except:
print("could not open the files - exiting")
sys.exit()
# The following will print any of the worksheet names (tabs)
print(wb.sheetnames)
# cycle through all of the worksheet(s)
for sheet in wb.sheetnames:
wb_current_sheet = wb[sheet]
ws = wb_current_sheet
ws_max_row = wb_current_sheet.max_row
ws_max_column = wb_current_sheet.max_column
print("max_rows = " + str(ws_max_row))
print("max_column = " + str(ws_max_column))
# the following loops through every cell in every row and column
for i in range(1, ws_max_row+1):
for j in range(1, ws_max_column+1):
try:
ws_cell_obj = ws.cell(row=i,column=j)
print(f"sheet={str(ws.title)} row={i},column={j} = {ws_cell_obj.value}")
except:
# if there's any exception, just print a "."
print(".")
pass
# This is the entry point for the program
if __name__ == "__main__":
# We do it this way so that we can handle arguments passed into the program
# The next line checks for the 'program name' and one argument
if len(sys.argv) != 2:
# A excel parser that reads every cell of every worksheet
# It should parse through any excel file that you pass to it
print("Usage:\nexcel_reader.py <input_file>\n\n")
sys.exit()
main(sys.argv[1])