Python中使用第三方库xlrd来读取Excel示例

yipeiwu_com5年前Python基础

本篇文章介绍如何使用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版本。

相关文章

完美解决Python2操作中文名文件乱码的问题

完美解决Python2操作中文名文件乱码的问题

Python2默认是不支持中文的,一般我们在程序的开头加上#-*-coding:utf-8-*-来解决这个问题,但是在我用open()方法打开文件时,中文名字却显示成了乱码。 我先给大家...

selenium 安装与chromedriver安装的方法步骤

selenium 安装与chromedriver安装的方法步骤

安装 selenium可以直接可以用pip安装。 pip install selenium chromedriver的安装一定要与Chrome的版本一致,不然就不起作用(不要问我是...

Python实现时钟显示效果思路详解

Python实现时钟显示效果思路详解

语言:Python IDE:Python.IDE 1.编写时钟程序,要求根据时间动态更新 2.代码思路 需求:5个Turtle对象, 1个绘制外表盘+3个模拟表上针+1个输出文字...

pygame学习笔记(2):画点的三种方法和动画实例

pygame学习笔记(2):画点的三种方法和动画实例

1、单个像素(画点) 利用pygame画点主要有三种方法: 方法一:画长宽为1个像素的正方形 复制代码 代码如下: import pygame,sys pygame.init() scr...

pandas基于时间序列的固定时间间隔求均值的方法

pandas基于时间序列的固定时间间隔求均值的方法

如果index是时间序列就不用转datetime;但是如果时间序列是表中的某一列,可以把这一列设为index 例如: 代码: DF=df2.set_index(df1['time_...