天天看點

python讀取excel(xlrd)

 一、安裝xlrd子產品:

1、mac下打開終端輸入指令:

2、驗證安裝是否成功:

在mac終端輸入 python  進入python環境

然後輸入 import xlrd

  不報錯說明子產品安裝成功

二、常用方法:

1、導入子產品:

2、打開檔案:

3、擷取sheet:

擷取所有sheet名字:x1.sheet_names()

擷取sheet數量:x1.nsheets

擷取所有sheet對象:x1.sheets()

通過sheet名查找:x1.sheet_by_name("test”)

通過索引查找:x1.sheet_by_index(3)

輸出:

4、擷取sheet的彙總資料:

擷取sheet名:sheet1.name

擷取總行數:sheet1.nrows

擷取總列數:sheet1.ncols

 5、單元格批量讀取:

 a)行操作:

sheet1.row_values(0)  # 擷取第一行所有内容,合并單元格,首行顯示值,其它為空。

sheet1.row(0)           # 擷取單元格值類型和内容

sheet1.row_types(0)   # 擷取單元格資料類型

b) 表操作

sheet1.row_values(0, 6, 10)   # 取第1行,第6~10列(不含第10表)

sheet1.col_values(0, 0, 5)    # 取第1列,第0~5行(不含第5行)

sheet1.row_slice(2, 0, 2)     # 擷取單元格值類型和内容

sheet1.row_types(1, 0, 2)   # 擷取單元格資料類型

6、特定單元格讀取:

 a) 擷取單元格值:

sheet1.cell_value(1, 2)

sheet1.cell(1, 2).value

sheet1.row(1)[2].value 

b) 擷取單元格類型:

sheet1.cell(1, 2).ctype

sheet1.cell_type(1, 2)

sheet1.row(1)[2].ctype

7、(0,0)轉換A1:

xlrd.cellname(0, 0)   # (0,0)轉換成A1

xlrd.cellnameabs(0, 0) # (0,0)轉換成$A$1

xlrd.colname(30)  # 把列由數字轉換為字母表示

8、資料類型:

空:0

字元串:1

數字:2

日期:3

布爾:4

error:5