2013-08-28 4 views
2

이전에 파이썬에서 작성한 일부 코드를 압축하려고합니다. 엑셀 워크 북에서 여러개의 룩업 테이블을 반복하는 코드가 있습니다. 통합 문서에 찾아보기 테이블이 포함 된 약 20 개의 시트가 있습니다. 각 룩업 테이블의 값을 반복하여 자신의 목록에 추가하려고합니다. 내 기존의 코드는 다음과 같습니다Dynamicaly Excel 통합 문서의 스프레드 시트에서 파이썬 목록 작성

test1TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test1TableList.append(row.Code) 

test2TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test2TableList.append(row.Code) 

test3TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test3TableList.append(row.Code) 

test4TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test4TableList.append(row.Code) 

test5TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test5TableList.append(row.Code) 

옹알 옹알

나는 (아마도 함수에서) 그 코드를 압축합니다.

문제 해결하기 :

  1. 시트 이름은 모두 다르다. a) 낱장 개체를 잡고 b) 시트 목록 이름을 파이썬 목록 변수 이름의 일부로 사용하려면 Excel 통합 문서의 각 시트를 반복해야합니다.
  2. 각 목록을 사용하기 위해 메모리에 추가로 저장하고 싶습니다. 코드

나는이 같은 작업을 노력했지만 파이썬 목록 변수는 메모리에 유지하지 않는 것 : 나는 잠시 동안이 작업을했습니다

import arcpy, openpyxl 
from openpyxl import load_workbook, Workbook 

wb = load_workbook(r"Z:\Excel\LOOKUP_TABLES.xlsx") 

for i in wb.worksheets: 

    filepath = r"Z:\Excel\LOOKUP_TABLES.xlsx" + "\\" + i.title + "$" 
    varList = [] 
    with arcpy.da.SearchCursor(filepath, '*') as cursor: 
     for row in cursor: 
      varList.append(row[0]) 

    # This is the area I am struggling with. I can't seem to find a way to return 
    # each list into memory. I've tried the following code to dynamically create 
    # variable names from the name of the sheet so that each list has it's own 
    # variable. After the code has run, I'd just like to set a print statement 
    # (i.e. print variablename1) which will return the list contained in the variable 
    newList = str(i.title) + "List" 
    newList2 = list(varList) 
    print newList + " = " + str(newList2) 

그리고 나는 의심의 여지가 없다,이 시점에서, 나는 나의 해결책을 생각하고 끝났지 만 나는 한 블록에있다. 모든 추천을 환영합니다! 대신 번식 목록을 갖는

+0

문제를 해결 했습니까? – alecxe

답변

1

는 당 시트 데이터를 수집하기 위해 사전을 사용 : 그것은 당신을 위해 최고

import arcpy 
from openpyxl import load_workbook 

wb = load_workbook(r"Z:\Excel\LOOKUP_TABLES.xlsx") 

sheets = {} 
for i in wb.worksheets: 
    filepath = r"Z:\Excel\LOOKUP_TABLES.xlsx" + "\\" + i.title + "$" 
    with arcpy.da.SearchCursor(filepath, '*') as cursor: 
     sheets[i.title] = [row[0] for row in cursor] 

print sheets 
3

확실하지 않음 경우, 그러나 당신은으로 시트를 가져올 팬더에게를 사용할 수 있습니다 데이터 프레임.

from pandas.io.excel import ExcelFile 
filename = 'linreg.xlsx' 
xl = ExcelFile(filename) 

for sheet in xl.sheet_names: 
    df = xl.parse(sheet) 
    print df 
+0

이 정확한 방법을 사용하고 있지만 빈 시트가 실행되면 코드가 충돌합니다. 이견있는 사람? – bejota

관련 문제