python脚本之将excel数据导入数据库并生成shp矢量数据

时常收到客户给的excel文件,含有(lon,lat)经纬度或者wkt数据,需要我们放到数据库里,发布要素图层服务,实现步骤:

  1. 读取excel数据
  2. 创建表
  3. 插入数据
  4. 生成矢量表
  5. 注册到空间数据库和生成空间索引
  6. 发布要素地图服务

以经纬度生成点和数据库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跑完后查询表:
在这里插入图片描述
生成矢量数据后,可根据具体情况,建议注册到数据库和生成空间索引后再发布地图服务,可加快相关的空间计算的速度和前端调用服务展示的速度。可参考:注册空间数据库和生成空间索引

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值