python 엑셀 읽 는 방법 패키지

오늘 은 엑셀 문서 (xls) 에서 데이터 베 이 스 를 가 져 오 는 표 가 필요 합 니 다. 처음에는 수 동 으로 한 줄 로 져 야 합 니 다.계속 그 럴 수 없다 고 생각 하고 파 이 썬 으로 다음 코드 를 써 서 이런 장면 에 쉽게 대처 할 수 있 었 다.예 를 들 어 내 가 봉 한 이런 방법 을 이용 하면 데 이 터 를 가 져 온 SQL 을 편리 하 게 만 들 수 있다.물론 엑셀 프로 그래 밍 에 익숙 한 학생 들 은 VBA 로 스 크 립 트 를 써 서 데 이 터 를 삽입 하 는 SQL 을 만 들 수도 있다.  또한. xls 파일 을. csv 파일 로 바 꾼 다음 에 SQLyog 나 Navicat 등 도 구 를 통 해 가 져 올 수 있 지만 세분 화 제어 할 수 없습니다 (예 를 들 어 특정한 조건 에 만족 하지 않 는 일부 데 이 터 는 가 져 올 필요 가 없고 프로그램 으로 더욱 세밀 하 게 제어 할 수 있 습 니 다. 예 를 들 어 중복 데 이 터 는 중복 가 져 올 수 없습니다. 또한 가 져 올 Excel 표 와 데이터 베이스 에 있 는 표 의 열 이 완전히 일치 하지 않 습 니 다) 。  나의 Python 버 전 은 3.0 입 니 다. xlrd 3, 전송 문 을 다운로드 해 야 합 니 다. http://pypi.python.org/pypi/xlrd3/ 그리고 setup. py install 명령 을 통 해 설치 하면 됩 니 다.
 
import xlrd3

'''
author: jxqlove?
            Excel     
'''


''' 
     
  Sheet     Sheet      ,     [ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex  sheet   ,0     sheet,    
xlsFilePath Excel           
'''
def getAllRowsBySheetIndex(sheetIndex, xlsFilePath):
    workBook = xlrd3.open_workbook(xlsFilePath)
    table = workBook.sheets()[sheetIndex]
    
    rows = []
    rowNum = table.nrows #     
    rowList = table.row_values
    for i in range(rowNum):
        rows.append(rowList(i)) #    rows.append(i, rowLists(i))
    
    return rows


'''
    Sheet       
sheetIndex 0  
rowIndex 0  
'''
def getRow(sheetIndex, rowIndex, xlsFilePath):
    rows = getAllRowsBySheetIndex(sheetIndex, xlsFilePath)
    
    return rows[rowIndex]


''' 
     
  Sheet     Sheet      ,     [ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex  sheet   ,0     sheet,    
xlsFilePath Excel           
'''
def getAllColsBySheetIndex(sheetIndex, xlsFilePath):
    workBook = xlrd3.open_workbook(xlsFilePath)
    table = workBook.sheets()[sheetIndex]
    
    cols = []
    colNum = table.ncols #     
    colList = table.col_values
    for i in range(colNum):
        cols.append(colList(i))
    
    return cols


'''
    Sheet       
sheetIndex 0  
colIndex 0  
'''
def getCol(sheetIndex, colIndex, xlsFilePath):
    cols = getAllColsBySheetIndex(sheetIndex, xlsFilePath)
    
    return cols[colIndex]


'''
    sheet            
'''
def getCellValue(sheetIndex, rowIndex, colIndex, xlsFilePath):
    workBook = xlrd3.open_workbook(xlsFilePath)
    table = workBook.sheets()[sheetIndex]
    
    return table.cell(rowIndex, colIndex).value #   table.row(0)[0].value  table.col(0)[0].value


if __name__=='__main__':
    rowsInFirstSheet = getAllRowsBySheetIndex(0, './  .xls')
    print(rowsInFirstSheet)

    colsInFirstSheet = getAllColsBySheetIndex(0, './  .xls')
    print(colsInFirstSheet)
    
    print(getRow(0, 0, './  .xls')) #      sheet      
    
    print(getCol(0, 0, './  .xls')) #      sheet      
    
    print(getCellValue(0, 3, 2, './  .xls')) #      sheet            

좋은 웹페이지 즐겨찾기