发布于 2015-04-08 04:58:59 | 296 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Python3 Cookbook中文版,程序狗速度看过来!

Python编程语言

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。


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



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务