[GIS] Import Cartesian coordinates from Excel and count its area

areacoordinatesexcelpython

I'm new and struggling with calculating xy area from Excel data ( or it can be any type of data with xy coordinates). Moreover according to task it must use all existing coordinates in Excel file.

How coordinates looks like

My code

import openpyxl


book = openpyxl.load_workbook('coordinates.xlsx')
sheet = book.active

for row_i in range(2, sheet.max_row + 1):
    x = sheet.cell(row=row_i, column=1).value
    y = sheet.cell(row=row_i, column=2).value
polygon = [[x,y]]
print(polygon)
area = 0.0
n = len(polygon)
for i in range(n):
    i1 = (i+1)%n
    area += polygon[i][0]*polygon[i1][1] - polygon[i1][0]*polygon[i][1]
area *= 0.5
print('area = ', area)

I don't know how to make that polygon = [[x,y]] would be like polygon [[608….,5105…],[6085…..,517…]], my code only picks last row data, I need that it pick all data and use it to calculate. Or if you have better idea, please share it.

Best Answer

It is picking the last because you are not appending to the array. Check below code:

import openpyxl


book = openpyxl.load_workbook('coordinates.xlsx')
sheet = book.active
polygon = []

for row_i in range(2, sheet.max_row + 1):
    x = sheet.cell(row=row_i, column=1).value
    y = sheet.cell(row=row_i, column=2).value
    polygon.append([x,y])

print(polygon)
area = 0.0
n = len(polygon)
for i in range(n):
    i1 = (i+1)%n
    area += polygon[i][0]*polygon[i1][1] - polygon[i1][0]*polygon[i][1]
area *= 0.5
print('area = ', area)
Related Question