时常收到客户给的excel文件,含有(lon,lat)经纬度或者wkt数据,需要我们放到数据库里,发布要素图层服务,实现步骤:
- 读取excel数据
- 创建表
- 插入数据
- 生成矢量表
- 注册到空间数据库和生成空间索引
- 发布要素地图服务
以经纬度生成点和数据库sql server为例,这里我们主要讲运用python脚本实现1-4步,读取excel数据导入数据库,并生成矢量数据的过程,python脚本如下:
#coding=utf-8
import pyodbc
import xlrd
##数据库连接
dbConn = pyodbc.connect('DRIVER={SQL Server};SERVER=100.211.98.11;DATABASE=gissde;UID=sa;PWD=Gis!@#sde')
cursor = dbConn.cursor()
##打开读取excel
def openExcel():
book = xlrd.open_workbook("test.xlsx") #打开excel的名字
sheet = book.sheet_by_name("Sheet1") #读取sheet的名字
rows = sheet.row_values(0) #读取第一行
row_num = sheet.nrows #计算有多少行
createTable(rows) #根据第一行字段创建表
insertTable(sheet,row_num) #从第二行开始插入数据
##创建表,建议此步骤也可在数据库中手动创建
def createTable(rows):
print (u"字段数量:" + str(len(rows))) #计算有多少列,即有多少字段
#根据列数确定字段下标数
city = rows[0]
code = rows[1]
lon = rows[2]
lat = rows[3]
#创建表sql 字段类型根据具体字段决定
sql_create_table = "create table A_TEST_EXCEL_TO_SQL"
sql_create_table += "(" + city + " varchar(50),"
sql_create_table += code + " varchar(50),"
sql_create_table += lon + " float,"
sql_create_table += lat + " float)"
print sql_create_table
cursor.execute(sql_create_table)
dbConn.commit()
print(u"新建表完成")
##插入数据
def insertTable(sheet,num):
print(u"开始插入数据")
for i in range(1,num):
row_data = sheet.row_values(i) #从第二行开始每一行的值
row_city = row_data[0] #第一列
row_code = row_data[1] #第二列
#需要将经纬度字段转为字符串类型才能做sql语句的拼接
row_lon = str(row_data[2]) #第三列
row_lat = str(row_data[3]) #第四列
#拼接sql插入语句
sql_insert_table = "insert into A_TEST_EXCEL_TO_SQL values('" + row_city + "','" + row_code + "'," + row_lon + "," + row_lat + ")"
cursor.execute(sql_insert_table)
dbConn.commit() #提交
print(u"数据插入完成")
toShape() #生成矢量数据
##生成矢量数据
def toShape():
print (u"开始生成矢量数据")
sql_to_shape = "select CAST(ROW_NUMBER() OVER(ORDER BY lon) as int) OBJECTID"
sql_to_shape += ",city,code,lon,lat"
sql_to_shape += ",geometry::Point(lon,lat,4326) shape" #经纬度转shape
sql_to_shape += " into A_TEST_EXCEL_TO_SQL_SHP"
sql_to_shape += " from A_TEST_EXCEL_TO_SQL where lon is not null and lat is not null"
print sql_to_shape
cursor.execute(sql_to_shape)
dbConn.commit()
print(u"生成矢量数据完成")
openExcel()
dbConn.close() #关闭数据库
测试excel数据量10000左右,总共耗时7秒左右,可见效率还是不错的
python跑完后查询表:
生成矢量数据后,可根据具体情况,建议注册到数据库和生成空间索引后再发布地图服务,可加快相关的空间计算的速度和前端调用服务展示的速度。可参考:注册空间数据库和生成空间索引