The module openpyxl is a convenient tool for users to process data in an excel table.
But it’s not build-in, we need to download the module manually after that developer can import and use it.
The following code snippet shows how to read data in excel file with openpyxl.

import openpyxl
wb = openpyxl.load_workbook( "/Users/weiyang/Downloads/automate_online-materials/example.xlsx" )
sheet1 = wb.get_active_sheet() #get_sheet_by_name('Sheet1')
#print sheet1['A1':'C7']
for objectsInRow in sheet1['A1':'C7']:
    for obj in objectsInRow:
        print( obj.coordinate, obj.value )
    print "=================="


We can calculate the math result of data in partial section. For instance, to get a summary of all values in the third column.

import openpyxl
wb = openpyxl.load_workbook( "/Users/weiyang/Downloads/automate_online-materials/example.xlsx" )
sheet1 = wb.get_sheet_by_name('Sheet1')

print "Calculate the summary of all values on 3 column"
objs = sheet1['C']
sum = 0
for cell in objs:
    sum = sum + int(cell.value)
print "sum is ",sum

Output:

$ python main.py
pythonCalculate the summary of all values on 3 column
sum is 497

 

Categories: Python

0 0 vote
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] wrote some simple examples about handling excel with python in article Read Excel Table With Python. Now let’s deal with a more complex task, to combine two different tables based on a common […]

A prohibited operation
1
0
Would love your thoughts, please comment.x
()
x