python定义xlsx数据维护excel的路径文件r_[转载]Python读取和写入Excel文件[整]

学习用Python处理Excel文件,这里主要用xlrd和xlwt模块,用前需要安装!本文是来自几篇博客和官网tutorial的整理,主要是一个入门。更多的处理Excel的方法请到官网学习,链接为:

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

A:Excel数据的类型及组织方式

每一个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():

6 #读取Excel表7 def

rExcel(self,inEfile,outfile):

8 rfile = xlrd.open_workbook(inEfile)

9 #创建索引顺序获取一个工作表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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值