Query the fields of an attribute table of a .shp file (ArcMap) from an .xlsm file with Python

2665
10
Jump to solution
06-03-2021 08:46 AM
BriamR
by
New Contributor II

I would like to know if there is any way through Python to query the fields of an attribute table of a .shp file (ArcMap) from an .xlsm file (Excel with macros enabled), this since what I currently do repetitively and manual is to copy the attribute table from ArcMap to my Excel file "VINCULACION_S.xlsm".

One of the attribute tables that I want to copy is the one I show in this image,

JosephBriamRamonRodriguez_1-1622745004422.png

Towards the .xlsm file already mentioned, which I show in this image.

JosephBriamRamonRodriguez_0-1622744959302.png

 

This is a good start apparently

 

# Set local variables

inTable = outTable

outXLS = VHFolder + "/Vinculacion_S.xlsx" #this is where I had to give the file path and then the file name

# Execute TableToExcel

arcpy.TableToExcel_conversion(inTable, outXLS)

ersion(inTable, outXLS)

 

 

 

Tags (3)
0 Kudos
10 Replies
BriamR
by
New Contributor II

I got this code as a solution to the post

import arcpy
import openpyxl as px

def main():
    wb = px.load_workbook(r"C:\Users\Hp\Desktop\Ejemplo\VINCULACION_S.xlsm", read_only=False, keep_vba=True)
    ws = wb['VINCULACION_SH_NUE']
    in_features = r"C:\Users\Hp\Desktop\Ejemplo\VH_Dissolve.shp"

    row_num = 3
    with arcpy.da.SearchCursor(
        in_features,
        ["COLOR", "INTERNO_DE", "CLASE_DEMA", "COUNT_AREA", "SUM_AREA", "SUM_LENGTH"],
    ) as cursor:
        for row in cursor:
            ws.cell(row=row_num, column=2).value = row[0]
            ws.cell(row=row_num, column=3).value = row[1]
            ws.cell(row=row_num, column=4).value = row[2]
            ws.cell(row=row_num, column=6).value = row[3]
            ws.cell(row=row_num, column=7).value = row[4]
            ws.cell(row=row_num, column=8).value = row[5]
            row_num += 1
    wb.save(r"C:\Users\Hp\Desktop\Ejemplo\VINCULACION_S.xlsm")