Python读取和写入Excel文件[整]

来源:互联网 发布:mysql和sql的区别 编辑:程序博客网 时间:2024/05/21 18:36

详见百度空间:http://hi.baidu.com/ilovelittree/item/62270cdf54fff132d80e4468


学习用Python处理Excel文件,这里主要用xlrdxlwt模块,用前需要安装!本文是来自几篇博客和官网tutorial的整理,主要是一个入门。更多的处理Excel的方法请到官网学习,链接为:http://www.simplistix.co.uk/presentations/python-excel.pdf

另外,几篇博客的参考资料:

http://syue.com/Software/Language/Python/21655.html

http://blog.csdn.net/wangxiaoyan1988/article/details/6562374

http://www.2cto.com/kf/201207/140006.html

 

 

AExcel数据的类型及组织方式


每一个Excel数据文件从上至下分为三个层级的对象:
workbook
 每一个Excel文件就是一个workbook
sheet
 每一个workbook中可以包含多个sheet,具体就对应Excel中我们在左下脚所看到的“sheet1”,“sheet2”等。
cell
 每一个sheet就是我们通常所看到的一个表格,可以含有m行,n列,每个确定的行号,列号所对应的一个格子就是一个cell

 

 

B: Excel中读取数据

从一个既有的xlsx文件中读取数据,按照Excel文件的三个层级,分别做以下三个步骤

 

1. 打开workbook

import xlrd
book = xlrd.open_workbook("myfile.xls")    #book
就赋值为一个Excel文件了

 

注:

Book 类的方法、属性等:即就可以对上面的book进行操作了
book.nsheets: 
 Book对象中的文件有多少个worksheet
book.sheet_by_index(sheetx):
 根据提供的sheetx索引来获取我们需要的sheet表,返回的是一个Sheet类的实例。
book.sheet_by_name(sheet_name):
 根据提供的sheet_name来获取对应名称的sheet类对象,返回的也是一个Sheet类的对象
book.sheet_names():
 Book对象中的所有sheet表的名称列表
book.sheets():
 返回在Book对象中所有的Sheet对象实例列表

 

2. 打开所需的sheet
sh = book.sheet_by_index(0)  #
获得一个sheet,也可以使名字获得
print sh.name, sh.nrows, sh.ncols

注:

Sheet类方法、属性等:
sh.cell(rowx, colx):
 根据给出的行和列的参数获取得到cell类,返回一个Cell类实例对象
sh.cell_type(rowx, colx):
 返回对应的cell对象的Type类型
sh.cell_value(rowx, colx):
 返回对应的cell对象的value
sh.col(colx):
 返回指定列的所有cell类对象序列
sh.name:
 返回sheet对象的名称
sh.ncols:
 返回在sheet对象中的列的数目
sh.nrows:
 返回在sheet对象中的行的数目
sh.row(rowx):
 返回指定的行的所有cell对象的序列

 

 

3. 获取对应cell的值:

cell=sh.cell(rowx=29, colx=3) #根据给出的行和列的参数获取得到cell类,返回一个Cell类实例对象

sh.cell_value(rowx=29, colx=3)

 

Cell类的属性、方法如下:
Cell
类对象有3种属性:ctype, value, xf_index
如果在excel文件打开的时候,formatting_info未启用的时候,xf_index是为None
下面列出了cell的类型,以及他们在python中所代表的值
type symbol          type number                python value
XL_CELL_EMPTY             0                     
 空的字符串''
XL_CELL_TEXT              1                      unicode
字符串
XL_CELL_NUMBER            2                      float
XL_CELL_DATE              3                      float
XL_CELL_BOOLEAN           4                      int;1 --- True,0 --- False
XL_CELL_ERROR             5                      int
代表是一个excel内部错误码;
XL_CELL_BLANK             6                     
 空的字符串'', 注意:这个类型仅仅会出现,当函数open_workbook(..,formatting_info=True)这样设置的时候

 

4.一个读取Excel的例子

 

import xlrd
book = xlrd.open_workbook("myfile.xls")
print "The number of worksheets is", book.nsheets
print "Worksheet name(s):", book.sheet_names()
sh = book.sheet_by_index(0)
print sh.name, sh.nrows, sh.ncols
print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
for rx in range(sh.nrows):
    print sh.row(rx)

 

 

C: Writing Excel Files

 

All the examples shown below can be found in the xlwt directory of the course material.Excel xlrd模块,写用xlwt模块

 

1.     Creating elements within a Workbook创建一个Excel文件

 

Import xlwt

wb=xlwt.Workbook(“zc.xls”) #Workbook 首字母大写

 

 

2.    Worksheets 添加Sheet

 

Worksheets are created with the add_sheet method of the Workbook class.

To retrieve an existing sheet from a Workbook, use its get_sheet method. This method is particularly useful when the Workbook has been instantiated by xlutils.copy.

 

Sheet1=wb.add_sheet(“sheetname”)

 

 

3.    Rows and Columns 行与列的表示:

 

row1 = sheet1.row(1)

col0=sheet2.col(0)

 

4.    Cells

 

Cells can be written using either the write method of either the Worksheet or Row class.

sheet1.write(0,1,'B1')

row1.write(0,'A2')

 

5.    svave  保存文件:

 

wb.save(“zc.xls”)

 

6.    Excel写入的一个简单的例子

from xlwt import Workbook

book = Workbook()

sheet1 = book.add_sheet('Sheet 1')  #添加一个sheet

book.add_sheet('Sheet 2')

sheet1.write(0,0,'A1')   #通过sheet添加cell

sheet1.write(0,1,'B1')

row1 = sheet1.row(1)

row1.write(0,'A2')     #还可以通过row属性添加cell

row1.write(1,'B2')

sheet1.col(0).width = 10000

sheet2 = book.get_sheet(1)

sheet2.row(0).write(0,'Sheet 2 A1')  #又一种添加

sheet2.row(0).write(1,'Sheet 2 B1')

sheet2.flush_row_data()

sheet2.write(1,0,'Sheet 2 A3')

sheet2.col(0).width = 5000

sheet2.col(0).hidden = True

book.save('simple.xls')

 

D 稍微复杂的例子和巩固

Ex1:

 

import xlrd
fname = "sample.xls"   #
一个文件路径和文件名
bk = xlrd.open_workbook(fname)    #
打开一个workbook
shxrange = range(bk.nsheets)   #
各个sheet之间的转换?
try:     #
提取sheet1
    sh = bk.sheet_by_name("Sheet1")
except:
    print "no sheet in %s named Sheet1" % fname
    return None
nrows = sh.nrows
ncols = sh.ncols
print "nrows %d, ncols %d" % (nrows, ncols)

cell_value = sh.cell_value(1,1)
print cell_value

row_list = []
for i in range(1, nrows):
    row_data = sh.row_values(i)
    row_list.append(row_data)

 

 

ex2:

 1

2 import xlrd
 3 import xlwt
 4
 5 class OperExcel():
   #
读取Excel
   def rExcel(self,inEfile,outfile):
     rfile = xlrd.open_workbook(inEfile)
     #
创建索引顺序获取一个工作表
10     table = rfile.sheet_by_index(0)
11     #
其他方式
12     #table = rfile.sheets()[0]
13     #table = rfile.sheet_by_name(u'Sheet1')
14
15     #
获取整行,整列的值
16     table.row_values(0)
17     table.col_values(0)
18
19     #
获取行数和列数
20     nrows = table.nrows - 1
21     ncols = table.ncols
22
23     #
循环获取列表的数据
24     #for i in range(nrows):
25     #  print table.row_values(i)
26     wfile = open(outfile,'w')
27     #
获取第一列中的所有值
28     for i in range(nrows):
29       #table.cell(i,0).value
获取某一单元格的值
30       wfile.write(table.cell(i,0).value.encode('utf8') + '\n')
31     wfile.close()
32
33 #
将数据写入Excel
34   def wExcel(self,infile,outEfile):
35     rfile = open(infile,'r')
36     buf = rfile.read().split('\n')
37     rfile.close()
38
39     w = xlwt.Workbook()
40     sheet = w.add_sheet('sheet1')
41     for i in range(len(buf)):
42       print buf[i]
43       sheet.write(i,0,buf[i].decode('utf8'))
44     w.save(outEfile)
45
46 if __name__ == '__main__':
47   t = OperExcel()
48   t.rExcel('test.xls','test')
49   t.wExcel('test','1.xls')

50 #  作者:sunrise

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 鼻子破皮了结痂怎么办 擤鼻子耳朵好像堵住了怎么办 鼻子和脸上起皮怎么办 鼻子擦鼻涕擦红怎么办 鼻子下面擦红了怎么办 鼻子擤鼻涕破皮怎么办 哭完鼻子不通气怎么办 擦鼻子擦多了疼怎么办 擤鼻涕时耳朵听不见了怎么办 吸鼻涕耳朵感觉被塞怎么办 擤鼻涕多了头疼怎么办 鼻子擤出鼻息肉怎么办 擤鼻涕鼻子破了怎么办 下水道里有鼻涕虫的怎么办 家里井口处有很多鼻涕虫怎么办 花生地里有蜗牛怎么办 菜园里有好多虫怎么办 心里莫名的急该怎么办 老感觉心烦气燥怎么办 什么事都不想做怎么办心里烦躁 咳嗽流鼻涕身体发热怕冷怎么办 不感冒流清鼻涕怎么办 刚怀孕感冒了怎么办鼻塞流鼻涕 孕妇打喷嚏流鼻涕怎么办速效办法 宝宝流鼻涕一个月了怎么办 一个月婴儿感冒咳嗽流鼻涕怎么办 怎么办感冒能好得快些 一个月的宝宝流鼻涕怎么办 鼻炎犯了一直流鼻涕怎么办 宝宝流鼻涕鼻子擦破了怎么办 宝宝流鼻涕鼻子擦红了怎么办 上班忘记穿内衣了怎么办 早上上班忘记穿内衣了怎么办 高中知识都忘了怎么办 留鼻涕跟水一样怎么办 鼻涕像水一样流怎么办 肩膀很疼怎么办睡不着觉 夏天穿内衣出汗后很臭怎么办 脸过敏后严重缺水怎么办 过敏后脸上反复出现湿疹怎么办 孕妇脸上长湿疹过敏红肿怎么办