Python 第三方庫xlrd讀取Excel代碼

Python 第三方庫xlrd讀取Excel代碼:

安裝xlrd

安裝xlrd,只需運行setup即可,另外你也可以直接解壓縮到你的project中,也可以直接用

xlrd的API

獲取Excel,這裏稱之爲work book

open_workbook(file_name)


獲取指定的Sheet,有兩種方式

sheet = xls.sheet_by_index(sheet_no)  

sheet = xls.sheet_by_name(sheet_name)


獲取整行和整列的值(數組)

sheet.row_values(i)   

sheet.col_values(i)


獲取總行數和總列數

nrows = sheet.nrows   

ncols = sheet.ncols


使用xlrd


使用xlrd這裏就用一個簡單的例子示例下:

# -*- coding: utf-8 -*-  

'''''  

Created on 2012-12-14  

 

@author:  walfred 

@module: XLRDPkg.read  

@description: 

'''    

import os  

import types  

import xlrd as ExcelRead  

 

def readXLS(file_name):  

    if os.path.isfile(file_name):  

        try:  

            xls = ExcelRead.open_workbook(file_name)  

            sheet = xls.sheet_by_index(0)  

        except Exception, e:  

            print "open %s error, error is %s" %(file_name, e)  

            return  

 

    rows_cnt = sheet.nrows  

    for row in range(1, rows_cnt):  

        name = sheet.row_values(row)[0].encode("utf-8").strip()  

        sex = sheet.row_values(row)[1].encode("utf-8").strip()  

        age = sheet.row_values(row)[2]  

        if type(age) is types.FloatType:#判讀下類型  

            no = str(int(age))  

        else:  

            age = no.encode("utf-8").strip()  

 

        country = sheet.row_values(row)[3].encode("utf-8").strip()  

        print "Name: %s, Sex: %s, Age: %s, Country: %s" %(name, sex, age, country)  

 

if __name__ == "__main__":  

    readXLS("./test_read.xls");

CODEGO.NET提醒,目前xlrd只支持95-03版本的MS Excel,所以使用之前需要覈對自己的word版本。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章