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


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


Categories: Python

1 Comment

Combine Two Excel Tables By Python – theArcticOcean · 2019年8月25日 at am11:27

[…] 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 […]

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page