python操作excel表格的方法

python操作excel表格的方法

 

可以用xlrd模块,需要另外下载
下载地址:http://pypi.python.org/pypi/xlrd
官网地址:http://www.python-excel.org/
文档地址:https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html
文档pdf下载:http://www.simplistix.co.uk/presentations/python-excel.pdf
在windows下直接安装就可以

 

1、导入模块
import xlrd

 

2、打开Excel文件读取数据
wb = open_workbook('new.xls')

 

3.读取所有工作表
sheets = wb.sheets()

 

经由过程open_workbook返回的xlrd.Book对象包含了所有对工作簿要的工作,能被用于在工作簿中取得自力的sheet。
这个nsheets属性是一个整数,包含工作簿sheet的数量。这个属性与sheet_by_index办法连络起来是获取自力sheet最常用的办法。
sheet_names办法返回包含工作簿中所有sheet名字的unicode列表。零丁的sheet可以经由过程sheet_by_name办法应用这些名字获取。
sheets办法的成果是迭代获取工作簿中的每个sheet。

 

4.读取cell对象

context = sh.cell(0,2).value

 

Sheet对象的cell办法能用来返回特定单位格的内容。
cell办法返回一个xlrd.sheet.Cell对象。除了value包含了单位格的真实值,ctype包含了单位格的类型,Cell对象几乎没有其他属性。
别的,Sheet对象有两个办法返回这两种数据类型。cell_value办法返回特定单位格的值,而cell_type办法返回特定单位格的类型。这两个办法履行时比获取Cell对象更快。

 

给个例子

from xlrd import *
import os
path = os.getcwd()
wb = open_workbook(path+'\\new.xls')

sheets = wb.sheets();
for i in range(0,len(sheets)):
    print "-----",sheets[i].name,"------"
    sh = wb.sheet_by_name(sheets[i].name)
    first_column = sh.col_values(0)
    second_column = sh.col_values(1)
    context = sh.cell(0,2).value
    for i in range(0,len(first_column)):
        print first_column[i],"\t",second_column[i]
    print context;

 


参考资料:http://www.byywee.com/page/M0/S636/636317.html

posted @ 2012-05-02 10:06  w0w0  阅读(446)  评论(0)    收藏  举报