#coding: UTF-8
import arcpy
import os
import types
import string
import shutil
import sys
import re
import openpyxl
#ws是一个xls的工作表
#mode是替换模型,1完全替换,2模糊替换,3 追加替换
def replacexls(ws,mode, text, replaceText):
rows = ws.max_row
cols = ws.max_column
changeCells=0
if (mode <0):
return -1
elif (mode>3):
return -1
for row in range(1, rows + 1):
for col in range(1, cols + 1):
try:
content = ws.cell(row=row, column=col).value
if (content != None):
# mode1: fullmatch replacement
if (mode == 1):
if (content == text):
ws.cell(row=row, column=col).value = replaceText
changeCells += 1
# mode2: partial replacement
elif (mode == 2):
if (type(content) == str):
ws.cell(row=row, column=col).value = content.replace(text, replaceText, 1)
changeCells += 1
# mode3: partialmatch and filling
elif (mode == 3):
if (type(content) == str):
ws.cell(row=row, column=col).value = content.replace(text, text + replaceText, 1)
changeCells += 1
except Exception as e:
print(traceback.format_exc())
return changeCells
def changeData(file, mode, text, replaceText):
# load the file(*.xlsx)
wb = openpyxl.load_workbook(file)
# ! deal with one sheet
ws = wb.worksheets[0]
replacexls(ws, mode, text, replaceText)
def initProgress(hint,num):
arcpy.SetProgressor("step", hint,0,num,1)
def step():
arcpy.SetProgressorLabel(u"waiting....")
arcpy.SetProgressorPosition()
def freeProgress():
arcpy.ResetProgressor()
def AddLayer(mxd,inFeature):
df=arcpy.mapping.ListDataFrames(mxd)[0]
addLayer = arcpy.mapping.Layer(inFeature)
arcpy.mapping.AddLayer(df, addLayer,"TOP") #AUTO_ARRANGE�?BOTTOM",TOP
#######
def getLayer(layername):
layername=layername.upper()
mxd = arcpy.mapping.MapDocument("CURRENT")
try:
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.name.upper()==layername:
return lyr
return None
finally:
del mxd
###
def midFill(sumn,mystr,Fill):
n=getlength(mystr)
if n>=sumn:
return mystr
leftn=int((sumn-n)/2)
s=""
lefts=s.ljust(leftn,Fill)
s=""
rightn=sumn-n-leftn
rights=s.ljust(rightn,Fill)
return lefts+mystr+rights
#获得一个表的记录数
def getCount(inFeature):
result = arcpy.GetCount_management(inFeature)
count= int(result.getOutput(0))
return count
def clearSelect(inFeature):
mylyr="mylyr"
arcpy.MakeFeatureLayer_management (inFeature, mylyr)
arcpy.SelectLayerByAttribute_management (mylyr, "CLEAR_SELECTION")
def validate_sheet_name(sheet_name):
""" Validate sheet name to excel limitations
- 31 character length
- there characters not allowed : \ / ? * [ ]
"""
import re
if len(sheet_name) > 31:
sheet_name = sheet_name[:31]
# Replace invalid sheet character names with an underscore
r = re.compile(r'[:\\\/?*\[\]]')
sheet_name = r.sub("_", sheet_name)
return sheet_name
#把内多边形,分解出来
def splitNgeometry(mgeometry):
num=mgeometry.count
Sumarray = arcpy.Array()
parray = arcpy.Array()
for i in range(num):
pt=mgeometry[i]
if pt:
parray.add(pt)
else:#内边形
Sumarray.add(parray)
parray.removeAll()
Sumarray.add(parray)
return Sumarray
def getJZDH(pgeometry):
mylayer="mylayer"
arcpy.MakeFeatureLayer_management(JZDFeature, mylayer)
arcpy.SelectLayerByLocation_management (mylayer, 'intersect',pgeometry )
num=getCount(mylayer)
cur = arcpy.da.SearchCursor(mylayer,[JZDHFieldName])
myJZDH=""
i=1
for row in cur:
myJZDH=row[0]
if cur:
del cur
return myJZDH
startrow=4
#获得点的距离
def pointDistance(pt1,pt2):
return math.sqrt((pt1.X-pt2.X)*(pt1.X-pt2.X)+(pt1.Y-pt2.Y)*(pt1.Y-pt2.Y))
def writeonexls(partgeometry,ws):
global startrow
num = partgeometry.count
for i in range(num):
pt = partgeometry[i]
x=pt.X
y=pt.Y
arcpy.AddMessage(str(x)+":"+str(y))
xstr="%.3f" % x
ystr="%.3f" % y
ws.cell(row=startrow, column=3).value=ystr
ws.cell(row=startrow, column=4).value=xstr
pointGeometry = arcpy.PointGeometry(pt)
JZDH=getJZDH(pointGeometry)
ws.cell(row=startrow, column=1).value = JZDH
if (i < num - 1):
pt2 = partgeometry[i+1]
linelen= pointDistance(pt,pt2)
ws.cell(row=startrow+1, column=2).value = "%.2f" %linelen
startrow=startrow+2
def writeXLS(ZDH,geometry):
scriptPath = sys.path[0]
toolSharePath =scriptPath #os.path.dirname(scriptPath)
myxls="界址点2000国家大地坐标系.xlsx" ##encode("GBK")
sFile=toolSharePath+u"/xls/"+myxls
tFile=outpath+"/"+ZDH+".xlsx"
arcpy.AddMessage(u"sFile"+sFile+","+tFile)
shutil.copyfile(sFile,tFile)
wb = openpyxl.load_workbook(tFile)
ws = wb.worksheets[0]
replacexls(ws, 2, "[宗地号]", ZDH)
area=geometry.area
replacexls(ws, 2, "[平方米]", '%.2f'% area)
area=area/10000
replacexls(ws, 2, "[公顷]", '%.4f' % area)
linelen= geometry.length
replacexls(ws, 2, "[总长]", '%.2f' % linelen)
global startrow
startrow = 4
part_count = geometry.partCount # 有几部分
pointcount=geometry.pointCount
replacexls(ws, 2, "[总节点]", '%d' % (pointcount+part_count-1) )
Sumarray = arcpy.Array()
for i in range(part_count):
partgeometry=geometry.getPart(i)
SpliArray=splitNgeometry(partgeometry)
N=SpliArray.count
#arcpy.AddMessage("NNNNN=====:"+str(N))
for j in range(N):
Splitgeometry=SpliArray[j]
writeonexls(Splitgeometry,ws)
wb.save(tFile)
def main():
num=getCount(ZDFeature)
if num<1:
arcpy.AddMessage(u"宗地没有数据")
return
clearSelect(JZDFeature)
num=getCount(JZDFeature)
if num<1:
arcpy.AddMessage(u"宗地没有数据")
return
for row in arcpy.da.SearchCursor(ZDFeature, ["OID@", "SHAPE@",ZDHFieldName]):
FID=row[0]
pgeometry=row[1]
ZDH=row[2]
writeXLS(ZDH,pgeometry)
def printauthor(toolname):
titlestr=""
sumn=60
Fill='*'
titlestr=titlestr.ljust(sumn,Fill)
arcpy.AddMessage(titlestr)
arcpy.AddMessage(midFill(sumn,u"欢迎使用:"+toolname,Fill))
mystr=u"本工具闫磊编写QQ:276529800,电话:18987281928"
arcpy.AddMessage(midFill(sumn,mystr,Fill))
mystr=u"使用前请做好数据备份,工具产生的不良后果请自行承担!"
arcpy.AddMessage(midFill(sumn,mystr,Fill))
arcpy.AddMessage(titlestr)
ZDFeature = arcpy.GetParameterAsText(0) #宗地
ZDHFieldName=arcpy.GetParameterAsText(1) #宗地号字段
JZDFeature=arcpy.GetParameterAsText(2) #输出数据
JZDHFieldName=arcpy.GetParameterAsText(3) #界址点号字段
outpath=arcpy.GetParameterAsText(4) #路径
arcpy.env.overwriteOutput=True
#printauthor(u"部标准坐标导入")
if not os.path.exists(outpath):
os.makedirs(outpath)
main()
==================================================
#coding: UTF-8
import arcpy
import os
import types
import string
import shutil
import xlwt
import xlrd
import sys
import re
import openpyxl
#ws是一个xls的工作表
#mode是替换模型,1完全替换,2模糊替换,3 追加替换
def replacexls(ws,mode, text, replaceText):
rows = ws.max_row
cols = ws.max_column
changeCells=0
if (mode <0):
return -1
elif (mode>3):
return -1
for row in range(1, rows + 1):
for col in range(1, cols + 1):
try:
content = ws.cell(row=row, column=col).value
if (content != None):
# mode1: fullmatch replacement
if (mode == 1):
if (content == text):
ws.cell(row=row, column=col).value = replaceText
changeCells += 1
# mode2: partial replacement
elif (mode == 2):
if (type(content) == str):
ws.cell(row=row, column=col).value = content.replace(text, replaceText, 1)
changeCells += 1
# mode3: partialmatch and filling
elif (mode == 3):
if (type(content) == str):
ws.cell(row=row, column=col).value = content.replace(text, text + replaceText, 1)
changeCells += 1
except Exception as e:
print(traceback.format_exc())
return changeCells
def changeData(file, mode, text, replaceText):
# load the file(*.xlsx)
wb = openpyxl.load_workbook(file)
# ! deal with one sheet
ws = wb.worksheets[0]
replacexls(ws, mode, text, replaceText)
def initProgress(hint,num):
arcpy.SetProgressor("step", hint,0,num,1)
def step():
arcpy.SetProgressorLabel(u"waiting....")
arcpy.SetProgressorPosition()
def freeProgress():
arcpy.ResetProgressor()
def AddLayer(mxd,inFeature):
df=arcpy.mapping.ListDataFrames(mxd)[0]
addLayer = arcpy.mapping.Layer(inFeature)
arcpy.mapping.AddLayer(df, addLayer,"TOP") #AUTO_ARRANGE�?BOTTOM",TOP
#######
def getLayer(layername):
layername=layername.upper()
mxd = arcpy.mapping.MapDocument("CURRENT")
try:
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.name.upper()==layername:
return lyr
return None
finally:
del mxd
###
def midFill(sumn,mystr,Fill):
n=getlength(mystr)
if n>=sumn:
return mystr
leftn=int((sumn-n)/2)
s=""
lefts=s.ljust(leftn,Fill)
s=""
rightn=sumn-n-leftn
rights=s.ljust(rightn,Fill)
return lefts+mystr+rights
#获得一个表的记录数
def getCount(inFeature):
result = arcpy.GetCount_management(inFeature)
count= int(result.getOutput(0))
return count
def clearSelect(inFeature):
mylyr="mylyr"
arcpy.MakeFeatureLayer_management (inFeature, mylyr)
arcpy.SelectLayerByAttribute_management (mylyr, "CLEAR_SELECTION")
def validate_sheet_name(sheet_name):
""" Validate sheet name to excel limitations
- 31 character length
- there characters not allowed : \ / ? * [ ]
"""
import re
if len(sheet_name) > 31:
sheet_name = sheet_name[:31]
# Replace invalid sheet character names with an underscore
r = re.compile(r'[:\\\/?*\[\]]')
sheet_name = r.sub("_", sheet_name)
return sheet_name
def writeXLS(ZDH,pgeometry):
scriptPath = sys.path[0]
toolSharePath =scriptPath #os.path.dirname(scriptPath)
myxls="界址点2000国家大地坐标系.xlsx" ##encode("GBK")
sFile=toolSharePath+u"/xls/"+myxls
tFile=outpath+"/"+ZDH+".xlsx"
arcpy.AddMessage(u"sFile"+sFile+","+tFile)
shutil.copyfile(sFile,tFile)
rb=xlrd.open_workbook(tFile)
rs = rb.sheet_by_index(0)
#ws = wb.get_sheet(0)
nrows = rs.nrows
ncols = rs.ncols
arcpy.AddMessage("nrows:"+str(nrows)+","+"ncols:"+str(ncols))
def main():
num=getCount(ZDFeature)
if num<1:
arcpy.AddMessage(u"宗地没有数据")
return
clearSelect(JZDFeature)
num=getCount(JZDFeature)
if num<1:
arcpy.AddMessage(u"宗地没有数据")
return
for row in arcpy.da.SearchCursor(ZDFeature, ["OID@", "SHAPE@",ZDHFieldName]):
FID=row[0]
pgeometry=row[1]
ZDH=row[2]
writeXLS(ZDH,pgeometry)
def printauthor(toolname):
titlestr=""
sumn=60
Fill='*'
titlestr=titlestr.ljust(sumn,Fill)
arcpy.AddMessage(titlestr)
arcpy.AddMessage(midFill(sumn,u"欢迎使用:"+toolname,Fill))
mystr=u"本工具闫磊编写QQ:276529800,电话:18987281928"
arcpy.AddMessage(midFill(sumn,mystr,Fill))
mystr=u"使用前请做好数据备份,工具产生的不良后果请自行承担!"
arcpy.AddMessage(midFill(sumn,mystr,Fill))
arcpy.AddMessage(titlestr)
ZDFeature = arcpy.GetParameterAsText(0) #宗地
ZDHFieldName=arcpy.GetParameterAsText(1) #宗地号字段
JZDFeature=arcpy.GetParameterAsText(2) #输出数据
JZDHFieldName=arcpy.GetParameterAsText(3) #界址点号字段
outpath=arcpy.GetParameterAsText(4) #路径
arcpy.env.overwriteOutput=True
#printauthor(u"部标准坐标导入")
if not os.path.exists(outpath):
os.makedirs(outpath)
main()