Excel needs no introduction, it's used almost every day, it's ubiquitous, it's easy to use, and they store structured data conveniently. Spreadsheets are very popular as a GIS format for collecting data.
I believe that you will encounter it in work or study, and convert the data in the spreadsheet into a Shapefile file. Next, we will demonstrate converting a spreadsheet to a Shapefile. The spreadsheet contains an x-field attribute column representing longitude and a y-field attribute column representing latitude . As shown in the following table:
import it into a Shapefile, the following steps will be performed:
(1) Open the spreadsheet;
(2) Create a shapefile writer object;
(3) Get the first row of the spreadsheet as the header of the dbf file;
(4) Loop through each row of the spreadsheet and copy the attributes to the dbf file;
(5) Create a point based on the values in the x and y fields in the spreadsheet.
import xlrd
import shapefile
# > (1)打开电子表格;
xls = xlrd.open_workbook(r"data/NYC_MUSEUMS_GEO.xlsx")
sheet = xls.sheet_by_index(0)
# > (2)创建一个shapefile文件写者对象;
with shapefile.Writer(r"data/NYC_MUSEUMS_GEO_toShp", shapefile.POINT) as w:
# column是列,row是行
# > (3)获取电子表格的第一行作为dbf文件的表头;
for i in range(sheet.ncols):
# print(sheet.cell(0,i))
# cell(行号,列号)
w.field(str(sheet.cell(0, i)), "C", 40)
# > (4)循环遍历电子表格每一行,将属性拷贝到dbf文件中;
for i in range(1,sheet.nrows):
values = []
for j in range(sheet.ncols):
values.append(sheet.cell(i,j).value)
w.record(*values)
# > (5)从最后两列获取经纬度信息,并创建点。
w.point(float(values[-2]),float(values[-1]))
The result is shown in the figure:
Summarize
Note: The latest xlrd does not support the reading of Excel xlsx files.
Method: Uninstall the latest xlrd library and install the historical version of the xlrd library. pip install xlrd == version number
pip install xlrd==1.2.0
"Python Geospatial Analysis Guide 2nd Edition" study notes, for learning only, please contact to delete if there is any infringement.