1. 程式人生 > >Python+xlrd

Python+xlrd

環境安裝

xlrd是python用於讀取excel的第三方擴充套件包,因此在使用xlrd前,需要使用以下命令來安裝xlrd。

pip install xlrd

xlrd基本用法

  1. 匯入擴充套件包
    import xlrd
    
  2. 開啟excel檔案
    excel = xlrd.open_workbook(u'excelFile.xls')
    
  3. 獲取工作表
    通過索引順序獲取
    table = excel.sheets()[0]
    table = excel.sheet_by_index(0)
    通過工作表名獲取
    table = excel.sheet_by_name(u'Sheet1')
    
  4. 獲取行數和列數
    獲取行數
    nrows = table.nrows
    獲取列數
    ncols = table.ncols
    
  5. 獲取整行或整列的值
    其中i為行號, j為列號
    行號、列號索引從0開始
    row_values = table.row_values(i)
    col_values = table.col_values(j)
    
  6. 獲取指定單元格資料
    i 行號, j 列號
    value = table.cell(i, j).value
    例如獲取第一行、第一列的資料
    value = table.cell(0, 0).value
    
  7. 迴圈行遍歷列表資料
    先獲取行數
    nrows = table.nrows
    遍歷列印所有行資料
    for i in range(0, nrows):
     print table.row_values(i)