arcpy 批量出图实战
要求:出某县各个村的功能划分图,数据源有地籍子区,地籍区,功能分布图,影像。
流程:用模型构建器搭建工作流导出一个村的一个要素类的数据库。建立一个mxd文档,加载源数据,设置好标题,图例,比例尺等。再用idle编写脚本。
代码很简单,但是花费了很多时间调试。遇到了很多问题,比如python2 中文乱码问题,layer.replaceDataSource的第三个参数只能为名字,不能带文件名的后缀等。
直接上代码。
import arcpy
import os
from arcpy import env
def GetgnFeafiles(gnfeadir):
gnfeafiles={}
env.workspace = gnfeadir
allfiles=arcpy.ListFeatureClasses()
for file in allfiles:
sp = “镇”
sp = sp.decode(‘gbk’)
cm = file.split(sp)[1]
gnfeafiles[cm] = file
return gnfeafiles
def GetFeafiles(feadir):
feafiles=[]
env.workspace = feadir
allfiles=arcpy.ListFeatureClasses()
for file in allfiles:
ff = feadir+”\\”+file
feafiles.append(ff)
return feafiles
path =”F:\\data\\lqhd\\xx\\cj.gdb” ##这里放cj的路径 ,记得打双斜杠
path = path.decode(‘gbk’)
gnpath = “F:\\data\\lqhd\\xx\\gn.gdb” ##这里放gn的路径 ,记得打双斜杠
gnpath = gnpath.decode(‘gbk’)
allshps=GetFeafiles(path)
gnfeas = GetgnFeafiles(gnpath)
mxdpath = “F:\\data\\lqhd\\cc.mxd” ##这里放cc.mxd的路径 ,记得打双斜杠
mxd=arcpy.mapping.MapDocument(mxdpath)
df = arcpy.mapping.ListDataFrames(mxd,”layer”)[0]
lyr=arcpy.mapping.ListLayers(mxd)[0]
lyrgn=arcpy.mapping.ListLayers(mxd)[4]
for shp in allshps:
paths=os.path.split(shp)
qianzhui = “xx县”
qianzhui = qianzhui.decode(‘gbk’)
houzhui = “粮食生产功能区划定工作底图”
houzhui = houzhui.decode(‘gbk’)
lyr.replaceDataSource(paths[0],”FILEGDB_WORKSPACE”,paths[1])
try:
lyrgn.replaceDataSource(gnpath,”FILEGDB_WORKSPACE”,gnfeas[paths[1]])
except:
print shp
layernamestr = gnfeas[paths[1]]
print layernamestr
titlename = qianzhui + layernamestr + houzhui
for elm in arcpy.mapping.ListLayoutElements(mxd,”TEXT_ELEMENT”):
if elm.name == “titlename”:
elm.text = titlename
lyr.visible =True
#lyr.showLabels =True
#lyr.labelClasses[0].expression = ‘[NAME]’
lyrExtent = lyr.getExtent()
df.extent = lyrExtent
arcpy.mapping.ExportToPNG(mxd,”F:\\data\res\\”+gnfeas[paths[1]]+”.png”) ##这里放存储结果的的路径 ,记得打双斜杠
print ‘ok’
转载自:https://blog.csdn.net/ydd0054/article/details/84590646