本文實例講述了Python讀取Excel的方法。分享給大家供大家參考。具體如下:
今天需要從一個Excel文檔(.xls)中導(dǎo)數(shù)據(jù)到數(shù)據(jù)庫的某表,開始是手工一行行輸?shù)摹:髞硐氩荒芤恢边@樣,就用Python寫了下面的代碼,可以很方便應(yīng)對這種場景。比如利用我封裝的這些方法可以很方便地生成導(dǎo)入數(shù)據(jù)的SQL。 當(dāng)然熟悉Excel編程的同學(xué)還可以直接用VBA寫個腳本生成插入數(shù)據(jù)的SQL。
還可以將.xls文件改為.csv文件,然后通過SQLyog或者Navicat等工具導(dǎo)入進來,但是不能細粒度控制(比如不滿足某些條件的某些數(shù)據(jù)不需要導(dǎo)入,而用程序就能更精細地控制了;又比如重復(fù)數(shù)據(jù)不能重復(fù)導(dǎo)入;還有比如待導(dǎo)入的Excel表格和數(shù)據(jù)庫中的表的列不完全一致) 。
我的Python版本是3.0,需要去下載xlrd 3: http://pypi.python.org/pypi/xlrd3/ 然后通過setup.py install命令安裝即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
import xlrd3 ''' author: jxqlove? 本代碼主要封裝了幾個操作Excel數(shù)據(jù)的方法 ''' ''' 獲取行視圖 根據(jù)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 # 總共行數(shù) 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] ''' 獲取列視圖 根據(jù)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 # 總共列數(shù) 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 , './產(chǎn)品.xls' ) print (rowsInFirstSheet) colsInFirstSheet = getAllColsBySheetIndex( 0 , './產(chǎn)品.xls' ) print (colsInFirstSheet) print (getRow( 0 , 0 , './產(chǎn)品.xls' )) # 獲取第一個sheet第一行的數(shù)據(jù) print (getCol( 0 , 0 , './產(chǎn)品.xls' )) # 獲取第一個sheet第一列的數(shù)據(jù) print (getCellValue( 0 , 3 , 2 , './產(chǎn)品.xls' )) # 獲取第一個sheet第四行第二列的單元格的值 |
希望本文所述對大家的Python程序設(shè)計有所幫助。