Python中使用第三方庫xlrd來讀取Excel樣本

來源:互聯網
上載者:User
本篇文章介紹如何使用xlrd來讀取Excel表格中的內容,xlrd是第三方庫,所以在使用前我們需要安裝xlrd。另外我們一般會使用xlwt來寫Excel,所以下一篇文章我們會來介紹如何使用xlwt來寫Excel。xlrd下載:xlrd 0.8.0

安裝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");

很easy吧,需要說明的是,目前xlrd只支援95-03版本的MS Excel,所以使用之前需要核對自己的word版本。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.