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

作者:junjie 时间:2022-04-22 06:29:41 

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

标签:Python,xlrd,读取,Excel
0
投稿

猜你喜欢

  • Python实现感知器模型、两层神经网络

    2021-11-14 07:34:19
  • Python模拟简单电梯调度算法示例

    2021-09-27 14:52:31
  • Flask入门教程实例:搭建一个静态博客

    2022-08-12 10:17:38
  • Go语言流程控制详情

    2023-10-16 13:16:24
  • python中利用队列asyncio.Queue进行通讯详解

    2023-02-13 03:52:58
  • python中pd.cut()与pd.qcut()的对比及示例

    2021-06-04 02:25:55
  • Python计算斗牛游戏概率算法实例分析

    2021-08-08 09:52:21
  • OpenCV中图像通道操作的深入讲解

    2022-02-13 02:39:22
  • python任务调度实例分析

    2021-06-30 12:42:57
  • python使用循环打印所有三位数水仙花数的实例

    2022-07-02 09:58:59
  • python调用staf自动化框架的方法

    2021-11-03 17:47:43
  • python实现textrank关键词提取

    2021-11-01 16:47:58
  • wxpython中自定义事件的实现与使用方法分析

    2023-02-10 07:50:26
  • python神经网络MobileNetV2模型的复现详解

    2023-08-19 16:20:44
  • Python列表list内建函数用法实例分析【insert、remove、index、pop等】

    2022-01-13 10:18:24
  • 将一个图片以二进制值的形式存入Xml文件中

    2008-09-04 11:24:00
  • 深入Python解释器理解Python中的字节码

    2022-04-28 18:29:33
  • php设计模式之正面模式实例分析【星际争霸游戏案例】

    2023-11-14 10:54:04
  • Recipe: 把SQL数据库部署到远程主机环境(第一部分)

    2007-09-23 13:07:00
  • python双向链表实现实例代码

    2023-05-16 09:38:54
  • asp之家 网络编程 m.aspxhome.com