這篇文章主要介紹了Python讀取Excel的方法,實例分析了Python操作Excel文件的相關技巧,非常具有實用價值,需要的朋友可以參考下
本文實例講述了Python讀取Excel的方法。分享給大家供大家參考。具體如下:
今天需要從一個Excel文檔(.xls)中導數據到數據庫的某表,開始是手工一行行輸的。后來想不能一直這樣,就用Python寫了下面的代碼,可以很方便應對這種場景。比如利用我封裝的這些方法可以很方便地生成導入數據的SQL。 當然熟悉Excel編程的同學還可以直接用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第四行第二列的單元格的值
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答