def f1(): ########## arcpy.env.workspace = "" rasters = arcpy.ListRasters() mask="" for raster in rasters: out = ExtractByMask(raster, mask) #"按掩膜提取" out.save("xxx/_34.tif") arcpy.Resample_management(raster, out, "xres yres", "BILINEAR") # "NEAREST ","BILINEAR","CUBIC","MAJORITY" #"重采样" arcpy.ExtractSubDataset_management("xxx.hdf", "outfile.tif", "2") #"提取子数据集,第三个参数是选择提取第几个子数据集(波段)" layer="" arcpy.MakeNetCDFRasterLayer_md(raster, "precipitation", "lon", "lat", layer) # "nc制作图层" arcpy.CopyRaster_management(layer, out, format="TIFF") # "图层保存为栅格" ExtractValuesToPoints(mask, raster,out, "INTERPOLATE","VALUE_ONLY") # "值提取到点"/"NONE","INTERPOLATE"/"VALUE_ONLY","ALL" out= SetNull(raster, raster, "Value=-3000") # "将满足条件的像元值设为Nodata" out=CellStatistics(rasters, out, "SUM", "NODATA") # "像元统计" "MEAN/MAJORITY/MAXIMUM/MEDIAN/MINIMUM/MINORITY/RANGE/STD/SUM/VARIETY " "NODATA"/"DATA"忽略nodata像元 out.save("xxx.img") arcpy.Delete_management(raster) # "删除文件" rasters = arcpy.ListRasters() # "数据的重命名" for raster in rasters: raster.save("xxx.tif") arcpy.TableToExcel_conversion(mask, "xxx.xls")# "表转Excel" arcpy.DirectionalDistribution_stats(raster, out, "1_STANDARD_DEVIATION", "xxx", "#")# "标准差椭圆" arcpy.MeanCenter_stats(raster, out, "xxx", "#", "#") # "中心"
def main(shp): curfields = set([f.name for f in arcpy.ListFields(shp)]) fields = set(['I', 'Y', 'X', 'No__Branch']) check = fields - curfields if len(check) != 0: arcpy.AddError( "Feature layer attributes not valid - run Topology Parameters tool" ) sys.exit() fname = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'plottopologydata.py') table = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'topology_table.xls') python_executer = r"C:\Python27\ArcGISx6410.6\python.exe" arcpy.env.workspace = os.path.dirname(table) arcpy.TableToExcel_conversion(shp, os.path.basename(table)) expression = [python_executer, fname, table] DETACHED_PROCESS = 0x00000008 P = subprocess.Popen(expression, shell=False, stdin=None, stdout=None, stderr=None, close_fds=True, creationflags=DETACHED_PROCESS)
def selectFeaturesExportToExcel(featureLayer, intersectLayer, bufDist, bufUnits, patts, outLocation): """ function to select layers by location and export selected features to an excel spreadsheet featureLayer = the feature layer to select records from intersectLayer = the layer to select the featureLayer against bufDist = the field in the intersectLayer containing the buffer distances bufUnits = the field in the intersectLayer containing the buffer units patts = PATTS ID for SARA site outLocation = the folder that output datasets are placed in. This is a user parameter in the tools' form """ # select layer by location - intersect arcpy.SelectLayerByLocation_management(featureLayer, 'INTERSECT', intersectLayer) # get count of selected features featuresCount = int(arcpy.GetCount_management(featureLayer)[0]) # if no features selected, add warning message if featuresCount == 0: # add warning message arcpy.AddWarning('\nNo features from {} intersect the {}-{} buffer'.format(featureLayer,bufDist,bufUnits)) # if features are selected, export them to excel file else: # name for excel file fileName = '{} Intersect {} {} {} Buffer.xls'.format(featureLayer,patts,bufDist,bufUnits) # output file outFile = os.path.join(outLocation,fileName) # export to excel arcpy.TableToExcel_conversion(featureLayer,outFile) # add message arcpy.AddMessage('\nExported features from {} layer that intersect the {}-{} buffer to a Microsoft Excel file'.format(featureLayer, bufDist, bufUnits)) # end if/else
def makeExcel(inGDB): # Enable extension for data reviewer and overwriting output. # arcpy.CheckOutExtension("datareviewer") arcpy.env.overwriteOutput = "true" target = inGDB.rindex('/') string1 = inGDB[target + 1:-11] # Set local variables print string1 in_data = inGDB + "/REVTABLEMAIN" out_data = inGDB + "/NoGeometry" # in_data = "Y:/Inventory/Michael/" + inGDB + "/REVTABLEMAIN" # out_data = "Y:/Inventory/Michael/" + inGDB + "/NoGeometry" # Execute Copy arcpy.Copy_management(in_data, out_data) dcursor = arcpy.da.UpdateCursor(out_data, '*') with arcpy.da.UpdateCursor(out_data, "*") as cursor: for row in cursor: if row[4] == 'Feature Record': cursor.deleteRow() with arcpy.da.SearchCursor(out_data, "*") as cursor: for row in cursor: # if row[4] == 'Feature Record': print row now = datetime.datetime.now() run = str(now)[:-16] print run in_table = out_data out_xls = "Y:/Inventory/Road Inventory Processes/Checks/Logs/" + run + string1 + "_Review_Table.xls" # out_xls = "Y:/Inventory/Michael/"+ run + str(inGDB)[:-4] + "Review_Table.xls" arcpy.TableToExcel_conversion(in_table, out_xls) return
def ExportReport(table, delta_date): env.overwriteOutput = True env.workspace = "Database Connections/RPUD_TRANSDB.sde" #env.workspace = os.path.join(os.path.dirname(sys.argv[0]), "RPUD_TESTDB - MOBILE_EDIT_VERSION.sde") #the name of database connection may need to be changed when in production #convert local time to UTC for query now = datetime.date.today().strftime('%Y%m%d') today = datetime.datetime(int(now[:4]), int(now[4:6]), int(now[6:]), 00, 00, 00) + datetime.timedelta(hours=4) yesterday = today - datetime.timedelta(days=delta_date) outputExcel = os.path.join("//corfile/Public_Utilities_NS/5215_Capital_Improvement_Projects/636_Geographic_Info_System/Joe/Collector App/Flushing app/Daily Report/", table + "_" + yesterday.strftime("%Y%m%d") + ".xls") logMessage("Input table is: " + table) logMessage("Output Excel file is: " + os.path.basename(outputExcel)) print ("Exporting table to Excel...") #query report table for records in previous day whereClause = '"CREATED_DATE" < timestamp \'{0}\' AND "CREATED_DATE" > timestamp \'{1}\' AND "CREW" NOT LIKE \'_GIS\' AND "CREW" NOT LIKE \'_test\' ORDER BY REPORT_DATE'.format(str(today), str(yesterday)) arcpy.MakeQueryTable_management(table, 'queryTable', "NO_KEY_FIELD", "", "", whereClause) recordNum = arcpy.GetCount_management('queryTable') logMessage(str(recordNum) + " " + table + " reports for " + (yesterday).strftime("%b %d, %Y")) #for test, print out fiels in queryTable # fields = arcpy.ListFields('queryTable') # for field in fields: # print("{0} is a type of {1}".format(field.aliasName, field.type)) #export queried table to excel, ALIAS option does not work here so far, need a solution arcpy.TableToExcel_conversion('queryTable', outputExcel, 'ALIAS') logMessage(os.path.basename(outputExcel) + " has been exported.") #return yesterday date for naming return yesterday, recordNum
def ExtractVals(nc, aoi, out): i = 0 for j in aoi: #Mask out raster with Marine Reserve limits and save it mask = arcpy.sa.ExtractByMask(nc, j) mask.save("SST_" + out[i] + ".TIF") #Create point features from masked out raster Pts = arcpy.RasterToPoint_conversion(mask, "SST_Pts" + out[i] + ".shp", "Value") #Extract values from multiple layers to point features SSTVal = arcpy.gp.ExtractMultiValuesToPoints_sa( Pts, "SST_" + out[i] + ".tif SST_" + out[i], "NONE") #Save attribute table of point features in excel format arcpy.TableToExcel_conversion(SSTVal, "SSTValues" + out[i] + ".xls", "NAME", "CODE") #Read excel table SSTPtVal = pd.ExcelFile("SSTValues" + out[i] + ".xls") #Load first excel sheet SST_sheet = SSTPtVal.parse(SSTPtVal.sheet_names[0]) #Create dictionary to change column names to months NewColNames = dict(zip(SST_sheet.columns[3:14], TimeLabs)) #Change column names using dictionary SST_sheet.rename(columns=NewColNames, inplace=True) #Write file with corrected column names into a csv file for further analysis SST_sheet.to_csv("SST_Values" + out[i] + ".csv") i += 1
def output_xls(in_table, out_xls): try: arcpy.TableToExcel_conversion(in_table, out_xls) return 1 except Exception as err: print(err.args[0]) return 0
def tabla2excel(tabla): ordenFields = [ "CODIGO_PENDIENTE", "X_PENDIENTE", "Y_PENDIENTE", "DISTANCIA", "CODIGO_COTIZADO", "ESTADO", "X_COTIZADO", "Y_COTIZADO", "CODIGO_N", "ZONAL", "JEFATURA", "EE_CC" ] tablaNueva = reorder_fields(tabla, TB_Final, ordenFields) arcpy.TableToExcel_conversion(tablaNueva, "clusters.xls")
def dmbiologist(pivotTable): pivotTableCOPY = arcpy.TableToTable_conversion(pivotTable, env.workspace, "pivotTableCOPY") with arcpy.da.UpdateCursor( pivotTableCOPY, ["dmproc", "total_records", "survey_site_dmstat"]) as cursor: for row in cursor: if row[0] == row[1] and (row[2] == "dmproc" or row[2] is None): cursor.deleteRow() else: pass refname = [ "hna", "geo", "lep", "eic", "tra", "dwa", "yea", "zim", "eaz", "alb", "kun", "mcp", "mil", "wis", "gip", "fur", "wal", "wat", "woo", "gle", "gru", "sch", "shc", "dav" ] createnames = [ "ahnatkovich", "bgeorgic", "bleppo", "ceichelberger", "ctracey", "dwatts", "dyeany", "ezimmerman", "ezimmerman", "jalbert", "jkunsman", "jmcpherson", "rmiller", "jwisgo", "kgipe", "mfuredi", "mwalsh", "dwatts", "pwoods", "rgleason", "sgrund", "sschuette", "sschuette", "ezimmerman" ] for ref, name in zip(refname, createnames): with arcpy.da.UpdateCursor(pivotTableCOPY, ["refcode", "created_by"]) as cursor: for row in cursor: if row[0] is None or row[1] is None: pass else: if (row[1].lower() == "arcgis" or row[1].lower() == "tjadmin" or row[1].lower() == "administrator" or row[1].lower() == "bgeorgic") and ref in row[0].lower(): row[1] = name cursor.updateRow(row) outPath = "P:\\Conservation Programs\\Natural Heritage Program\\" \ "Data Management\\Instructions, procedures and documentation\\FIND\\" \ "FIND_2016\\Reports\\Biologist Status Reports" with arcpy.da.SearchCursor(pivotTableCOPY, "created_by") as cursor: biologists = sorted({row[0] for row in cursor}) for biologist in biologists: if biologist is None: pass else: expression = "created_by = '{}'".format(biologist) tableTEMP = arcpy.TableToTable_conversion(pivotTableCOPY, "in_memory", "tableTEMP", expression) filename = biologist + " - " + "FIND Status Report " + time.strftime( "%d%b%Y") + ".xls" outTable = os.path.join(outPath, filename) arcpy.TableToExcel_conversion(tableTEMP, outTable) print "DM Biologist Report Created!"
def output(kind, zField): # Processing global cell_size, doPoints, doRaster, doASC if doOverWrite: cleanDirs(kind) env.workspace = path + kind + ".gdb" env.snapRaster = path + "Area\\Area.tif" env.extent = path + "Area\\Area.tif" env.parallelProcessingFactor = "0" points = path + "Area\\points.shp" locations = path + kind + "\\" dirs = os.listdir(locations) for file in dirs: in_point_features = file.rstrip('.csv') try: out = Kriging(in_point_features, zField, KrigingModelOrdinary(), cell_size) except Exception as e: out = Idw(in_point_features, zField, cell_size) pass midRaster = path + kind + "MID\\" + "MID_" + file.rstrip( '.csv') + ".tif" out.save(midRaster) if doPoints: # Different situations outPoint = path + kind + "MID\\Points\\" + file.rstrip( ".csv") + ".shp" ExtractValuesToPoints(points, midRaster, outPoint) outExcel = path + kind + "XLS\\" + file.rstrip(".csv") + ".xls" arcpy.TableToExcel_conversion(outPoint, outExcel) pass if doRaster and not doASC: clipped = path + kind + "TIF\\" + file.rstrip(".csv") + ".tif" raster = ExtractByMask(midRaster, path + "Area\\Area.tif") raster.save(clipped) continue if doRaster and doASC: clipped = path + kind + "TIF\\" + file.rstrip(".csv") + ".tif" raster = ExtractByMask(midRaster, path + "Area\\Area.tif") raster.save(clipped) outASCII = path + kind + "ASC\\" + file.rstrip('.csv') + '.asc' arcpy.RasterToASCII_conversion(clipped, outASCII) continue if not doRaster and doASC: clipped = path + kind + "MID\\Raster\\" + file.rstrip( ".csv") + ".tif" raster = ExtractByMask(midRaster, path + "Area\\Area.tif") raster.save(clipped) outASCII = path + kind + "ASC\\" + file.rstrip('.csv') + '.asc' arcpy.RasterToASCII_conversion(clipped, outASCII) continue return
def f2(): wb = xlwt.Workbook(encoding='ascii') ws1 = wb.add_sheet('IMERG') RGS = 'F:/SA/TEMP/RGS.shp' for y in range(15, 18): arcpy.env.workspace = 'F:/SA/DATA/0/TIFAREA1/' + 'IMERGD' + '/' + 'M' + '/' + str( 2000 + y) + '/' rasters = arcpy.ListRasters() path = 'F:/SA/RG/' + 'IMERGD' + '/' + 'M' + '/' + str(2000 + y) + '/' for m in range(0, len(rasters)): shp = path + 'I' + str((2000 + y) * 100 + m + 1) + '.shp' ExtractValuesToPoints(RGS, rasters[m], shp, "NONE", "VALUE_ONLY") xls = path + 'I' + str((2000 + y) * 100 + m + 1) + '.xls' arcpy.TableToExcel_conversion(shp, xls) d = xlrd.open_workbook(xls) t = d.sheet_by_index(0) a = t.col_values(3, 1, 84) for i in range(0, 83): ws1.write(i, (y - 15) * 12 + m, a[i]) ws2 = wb.add_sheet('IMERGM') for y in range(15, 18): arcpy.env.workspace = 'F:/SA/DATA/0/TIFAREA1/' + 'IMERGM' + '/' + 'M' + '/' + str( 2000 + y) + '/' rasters = arcpy.ListRasters() path = 'F:/SA/RG/' + 'IMERGM' + '/' + 'M' + '/' + str(2000 + y) + '/' for m in range(0, len(rasters)): shp = path + 'IM' + str((2000 + y) * 100 + m + 1) + '.shp' print(rasters[m]) ExtractValuesToPoints(RGS, rasters[m], shp, "NONE", "VALUE_ONLY") xls = path + 'IM' + str((2000 + y) * 100 + m + 1) + '.xls' arcpy.TableToExcel_conversion(shp, xls) print(xls) d2 = xlrd.open_workbook(xls) t2 = d2.sheet_by_index(0) a2 = t2.col_values(3, 1, 84) for i in range(0, 83): ws2.write(i, (y - 15) * 12 + m, a2[i]) out = 'F:/SA/RAIN/RAIN3/' + "test.xls" wb.save(out)
def BatchExtractValuesToPoints(Input_Landsat_dir, gdb, src_featureClass, outputTable_dir): PATTERN = re.compile(r'^[0-9a-zA-Z]*_[0-9a-zA-Z]*_(\d*)_(\d*)\w*\.tif$') if not os.path.exists(outputTable_dir): os.makedirs(outputTable_dir) YEARS_DIR = os.listdir(Input_Landsat_dir) for year_dir in YEARS_DIR: year_path = os.path.join(Input_Landsat_dir, year_dir) file_dict = {} if os.path.isdir(year_path): print("processing " + Input_Landsat_dir + ": year " + year_dir) files = os.listdir(year_path) for fname in files: fpath = os.path.join(year_path, fname) if os.path.isfile(fpath) and fpath.endswith(".tif"): mo = PATTERN.match(fname) ymd = mo.group(2) if not ymd in file_dict: file_dict[ymd] = [] file_dict[ymd].append(fname) # print(mo.group(1), mo.group(2)) keys = sorted(file_dict.keys()) inRasterList = [] for k in keys: f_list = sorted(file_dict[k]) for f in f_list: inRasterList.append([f, k]) # print(inRasterList) # Local variables: Zjt_org = gdb + "/" + src_featureClass featureClasses = src_featureClass + "_" + str(year_dir) inPointFeatures = gdb + "/" + featureClasses # Process: Copy arcpy.Copy_management(Zjt_org, inPointFeatures, "FeatureClass") # Execute ExtractValuesToPoints arcpy.env.workspace = year_path arcpy.sa.ExtractMultiValuesToPoints(inPointFeatures, inRasterList, "NONE") # TableToDBASE_conversion # arcpy.TableToDBASE_conversion( inPointFeatures, output_dir) # Local variables: # Zjt_1995 = "C:/ignrr/data/LT05/Zjt.gdb/Zjt_1995" # print("outputTableDir:" + outputTable_dir) zjt_xls = os.path.join(outputTable_dir, featureClasses + ".xls") # print(zjt_xls) # Process: Table To Excel arcpy.TableToExcel_conversion(inPointFeatures, zjt_xls, "ALIAS", "CODE")
def AttributeTabletoDF_Old(FC): f = os.path.basename(FC) ExOut = CreateOutPath( os.path.join(os.getcwd(), f + '_' + strftime("%Y%m%d%H%M%S")) + str(np.random.normal()), 'Out', 'xlsx') arcpy.TableToExcel_conversion(FC, ExOut) DF = pd.read_excel(ExOut) arcpy.Delete_management(ExOut) return (DF)
def DBF2EXCEL(input_path, output_path): ''' :param input_path: 待转换的dbf文件所在文件夹 :param output_path: 生产的csv文件存放的文件夹 :return: ''' for dbffile in os.listdir(input_path): if os.path.splitext(dbffile)[1] == '.dbf': # 过滤其他后缀文件 inputfile = input_path + dbffile outputfile = output_path + os.path.splitext(dbffile)[0] + '.xls' print(outputfile) arcpy.TableToExcel_conversion(inputfile, outputfile)
def outputProportions(intable, outtype, outpath, outfilename, outfullpath): if outtype == "dBASE": # Process: Table To Table arcpy.AddMessage("Exporting to %s DBASE located to directory %s" % (outfilename, outpath)) print "Exporting to dBASE" arcpy.TableToTable_conversion(intable, outpath, outfilename) elif outtype == "Excel (.xls)": # Process: Table To Excel arcpy.AddMessage("Exporting to %s Excel to directory %s" % (outfilename, outpath)) arcpy.TableToExcel_conversion(intable, outfullpath, "NAME", "CODE")
def dmpending(pivotTable): pivotTableCOPY = arcpy.TableToTable_conversion(pivotTable, env.workspace, "pivotTableCOPY") with arcpy.da.UpdateCursor(pivotTableCOPY, "survey_site_dmstat") as cursor: for row in cursor: if row[0] == "dmpend": pass else: cursor.deleteRow() filename = "DM Pending " + time.strftime("%d%b%y") + ".xls" outTable = os.path.join(ReportsPath, filename) arcpy.TableToExcel_conversion(pivotTableCOPY, outTable) print "DM Pending Report Created!"
def TableToExcel(TableLocation, OutputFolder): ''' This function takes a database (string) that contains tables that the user wants to export to Excel. The output folder where those Excel files will be stored is also needed as a parameter (string). ''' arcpy.env.workspace = TableLocation Tables = arcpy.ListTables() for Table in Tables: OutputExcel = Table + ".xls" OutputPath = os.path.join(OutputFolder, OutputExcel) print OutputPath arcpy.TableToExcel_conversion(Table, OutputPath) print 'done creating Excel files'
def saveExcel(pivotTable): # save output as excel file on the P: drive with date in filename----------- outPath = "P:\Conservation Programs\Natural Heritage Program\Data Management" \ "\Instructions, procedures and documentation\FIND\FIND_2016\Reports" if reportType.lower() == "dm pending": filename = "DM Pending " + time.strftime("%d%b%Y") + ".xls" elif reportType.lower() == "dm ready": filename = "DM Ready " + time.strftime("%d%b%Y") + ".xls" elif reportType.lower() == "dm total": filename = "DM Total " + time.strftime("%d%b%y") + ".xls" outTable = os.path.join(outPath, filename) arcpy.TableToExcel_conversion(pivotTable, outTable)
def export_domains(domains): for domain in domains: arcpy.AddMessage('Exporting %s CV to table in %s' % (domain.name, gdb)) table = os.path.join(gdb, domain.name) arcpy.DomainToTable_management(gdb, domain.name, table, 'field', 'descript', '#') if xls: os.chdir(gdb) os.chdir('..') xlsfile = '%s_%s.xls' % (os.path.join( os.path.basename(gdb)), domain.name) arcpy.AddMessage('Exporting %s CV to table in %s' % (domain.name, xlsfile)) arcpy.TableToExcel_conversion(table, xlsfile)
def exportToExcel(out_table, xls_path): # On demande au user s'il desire effectuer une exportation du resultat sous excel print("Veuillez tapez: ") print("1 >>> pour exporter le resultat sous excel") print("2 >>> pour quitter le programme") rep = input("Entrer votre choix : ") if rep==1: print("Lancement exportation sous excel ...") arcpy.TableToExcel_conversion(out_table, xls_path) print("Exportation effectuée avec succès ...") elif rep==2: print("Fin du programme.") else: print("Fin du programme.")
def dmtotal(pivotTable): pivotTableCOPY = arcpy.TableToTable_conversion(pivotTable, env.workspace, "pivotTableCOPY") with arcpy.da.UpdateCursor( pivotTableCOPY, ["dmproc", "total_records", "survey_site_dmstat"]) as cursor: for row in cursor: if row[0] == row[1] and row[2] == "dmproc": cursor.deleteRow() elif row[0] == row[1] and row[2] is None: cursor.deleteRow() else: pass filename = "DM Total " + time.strftime("%d%b%y") + ".xls" outTable = os.path.join(ReportsPath, filename) arcpy.TableToExcel_conversion(pivotTableCOPY, outTable)
def to_excel(): excel_folder = "c:/XXX/XXX/XXX/" # <-- MODIFY as needed master_list = arcpy.ListFeatureClasses() list1 = [] for name in master_list: if "final" in name: # <-- MODIFY as needed list1.append(name) print "List1 now includes:", list1 else: print "File %s has been excluded from List1." % name for filename in list1: arcpy.TableToExcel_conversion(filename, excel_folder + filename + "_excel.xls") # <-- MODIFY as needed print "File %s's table has now been converted to an Excel table." % filename
def ExportToExcel(input_table, Project_Folder, Project_Name): """ Exports the attribute table of the provided feature or table as a .xls file and saves to the project folder with the project name appended. :param input_table: a table to be exported :param Project_Folder: the directory of the project's unique folder :param Project_Name: the unique name of the project as a string :return: None """ # Update message arcpy.AddMessage("Exporting " + str(input_table) + " attribute tables to " "Excel within the Project Folder") # Export tables output_file = os.path.join(Project_Folder, str(Project_Name) + "_" + str(input_table) + ".xls") arcpy.TableToExcel_conversion(input_table, output_file)
def dmready(pivotTable): '''function that creates report of all records that are ready for DM''' # create copy of pivot table pivotTableCOPY = arcpy.TableToTable_conversion(pivotTable, env.workspace, "pivotTableCOPY") # delete all records unless all features and survey site are marked dm ready with arcpy.da.UpdateCursor(pivotTableCOPY, ["dmready","dmproc", "total_records", "survey_site_dmstat"]) as cursor: for row in cursor: if (row[0]+row[1] == row[2]) and (row[0] > 0) and (row[3] == "dmready" or row[3] == "dmproc"): pass else: cursor.deleteRow() # export table as Excel file to produce final report filename = "DM Ready_" + time.strftime("%d%b%y")+".xls" outTable = os.path.join(ReportsPath, "DM Status Reports", filename) arcpy.TableToExcel_conversion(pivotTableCOPY, outTable) print("DM Ready Report Created!")
def dmtotal(pivotTable): '''function that creates report of all unprocessed records in FIND''' # create copy of pivot table pivotTableCOPY = arcpy.TableToTable_conversion(pivotTable, env.workspace, "pivotTableCOPY") # delete records when all features are processed with arcpy.da.UpdateCursor(pivotTableCOPY, ["dmproc", "total_records", "survey_site_dmstat"]) as cursor: for row in cursor: if row[0] == row[1] and row[2] == "dmproc": cursor.deleteRow() elif row[0] == row[1] and row[2] is None: cursor.deleteRow() else: pass # export table as Excel file to produce final report filename = "DM Total_" + time.strftime("%d%b%y")+".xls" outTable = os.path.join(ReportsPath, "DM Status Reports", filename) arcpy.TableToExcel_conversion(pivotTableCOPY, outTable)
def func_5(): inPath = "F:/Test/GraduationWork/Data/Temp/HBAL" inFile = os.path.join(inPath, "SK_323_20190802.csv") # SK_323_201801_06 outFile = os.path.join(inPath, "TempDaily.csv") points= "F:/Test/GraduationWork/Data/Points/Points82.shp" outCsv = 'F:/Test/GraduationWork/Data/Temp/PreOf82RGS.csv' env.workspace =inPath rasList=arcpy.ListRasters() env.workspace = "F:/Test/GraduationWork/Data/Temp/0/" for ras in rasList: namePieces=ras.split('_') tempShp=namePieces[0]+namePieces[1]+'_RG82.shp' file=os.path.join(inPath,ras) print(file) ExtractValuesToPoints(points, file, tempShp,"INTERPOLATE", "VALUE_ONLY") outExcels = namePieces[0]+namePieces[1]+'_RG82' + '.xls' arcpy.TableToExcel_conversion(tempShp, outExcels) # "表转Excel"
def GDBAudit(GDBItems, GDBItemType, OutputLocation): # GDB Items to scratch table writelog(logFile, "Process: GDB Items to scratch table" + "\n") GDB_ITEMSTable = arcpy.TableToTable_conversion(GDBItems, arcpy.env.scratchGDB, "GDB_ITEMSTable", "", "", "") writelog(logFile, "Process: GDB Items to scratch table Complete!" + "\n") # Delete Fields writelog(logFile, "Process: Delete Fields" + "\n") GDB_ITEMSTable = arcpy.DeleteField_management(GDB_ITEMSTable, "Definition;Documentation") writelog(logFile, "Process: Delete Fields Complete!" + "\n") # GDB ITem Type to Scratch Table writelog(logFile, "Process: GDB ITem Type to Scratch Table" + "\n") GDB_ITEMTPYESTable = arcpy.TableToTable_conversion( GDBItemType, arcpy.env.scratchGDB, "GDB_ITEMTPYESTable", "", "", "") #arcpy.env.scratchGDB writelog(logFile, "Process: GDB ITem Type to Scratch Table Complete!" + "\n") # Run Join Field GDP tool to put the GDB_ITEMS table and the GDB_ITEMTYPES table together writelog( logFile, "Process: Run Join Field GDP tool to put the GDB_ITEMS table and the GDB_ITEMTYPES table together" + "\n") GDB_ITEMSTable = arcpy.JoinField_management(GDB_ITEMSTable, "Type", GDB_ITEMTPYESTable, "UUID", "Name;ParentTypeID") writelog( logFile, "Process: Run Join Field GDP tool to put the GDB_ITEMS table and the GDB_ITEMTYPES table together Complete!" + "\n") # Table to Excel Conversion tool writelog(logFile, "Table to Excel Conversion tool" + "\n") arcpy.TableToExcel_conversion(GDB_ITEMSTable, OutputLocation, "NAME", "CODE") writelog(logFile, "Table to Excel Conversion tool Complete!" + "\n") writelog(logFile, "Table Located: " + str(OutputLocation) + "\n")
def dmpending(pivotTable): '''function that creates report of records with at least one feature marked as DM Pending''' # create copy of pivot table pivotTableCOPY = arcpy.TableToTable_conversion(pivotTable, env.workspace, "pivotTableCOPY") # delete all records that do not have at least one feature marked DM Pending with arcpy.da.UpdateCursor(pivotTableCOPY, "survey_site_dmstat") as cursor: for row in cursor: if row[0] == "dmpend": pass else: cursor.deleteRow() # export table as Excel file to produce final report filename = "DM Pending " + time.strftime("%d%b%y")+".xls" outTable = os.path.join(ReportsPath, "DM Status Reports", filename) arcpy.TableToExcel_conversion(pivotTableCOPY, outTable) print("DM Pending Report Created!")
def f2_GCS(): path = 'F:/Test/Paper180829/Data/IMERG/' arcpy.env.workspace = path + 'originIMERG/' rasters = arcpy.ListRasters() for raster in rasters: outResample = path + '0.1dIMERG/' + raster arcpy.Resample_management(raster, outResample, "0.1", "BILINEAR") # "重采样到0.1度" mask = 'F:/Test/Paper180829/Data/HB/' + 'HB8048.shp' outExtract = ExtractByMask(outResample, mask) # "按掩膜提取" outExtract.save(path + '0.1d8048/' + raster) points = 'F:/Test/Paper180829/Data/POINT/' + 'POINTS83.shp' outPoints = path + '0.1dRG83/' + raster[0:7] + '.shp' ExtractValuesToPoints(points, outExtract, outPoints, "INTERPOLATE", "VALUE_ONLY") # "值提取到点" outExcels = path + '0.1dExcels/' + raster[0:7] + '.xls' arcpy.TableToExcel_conversion(outPoints, outExcels) # "表转Excel"
def get_pl_anomalies(in_table, out_table, sql_condition, excelOutput): # export param is a boolean fields=["OBJECTID", "SHAPE", "METER_NUMBER", "CLIENT_NAME", "CONTRACT_NUMBER", "SERVICE_STATUS", "Contrat_Facture_Terrain", "Compteur_Terrain", "Type_Compteur", "Phasage_Compteur", "Calibre_Disjoncteur", "Reglage_Disjoncteur", "Norme_Branchement", "Index", "Etat_Compteur", "Activite_Principale", "Type_Construction", "Distributeur_Coffret", "Anomallies", "CCFBD", "BCC", "Famille_Activite", "Photo", "NB_Roues", "Compteur_Scelle", "Disjoncteur_Scelle", "Coffret_Scelle", "Visibilite_Cable", "Accessibilite_Compteur", "Disjoncteur", "Code_Transfo", "Date_de_visite", "Data_Creator", "Observations", "CONFIRMATION_INDEX"] #------------------ Traitement de la liste des champs de l'input PL feature class -------------------------------- Fields1 = arcpy.ListFields(in_table) Fields2 = arcpy.ListFields(out_table) #fields1 = list() #fields2 = list() ## for field in fields1: ## fields1.append(field) ## ## for field3 in fields2: ## fields2.append(fiel3) cursor = arcpy.da.SearchCursor(in_table, fields, sql_condition) cursorInsert = arcpy.da.InsertCursor(out_table, fields) cpt=0 arcpy.AddMessage("Count fields = " + str(len(fields))) for row in cursor: cursorInsert.insertRow(row) cpt+=1 arcpy.AddMessage("Export the result to excel ...") arcpy.TableToExcel_conversion(out_table, excelOutput) arcpy.AddMessage("Export to excel done succesfully.") arcpy.AddMessage("{0} rows inserted ".format(str(cpt))) #On supprime de le curseur d'insertion del cursorInsert