Python读取和写入Excel文件

学习用Python处理Excel文件,这里主要用xlrd和xlwt模块,用前需要安装!本文是来自几篇博客和官网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.    save  保存文件:

 

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:

import xlrd
import xlwt

class OperExcel():
 #读取Excel表
def rExcel(self,inEfile,outfile):
     rfile = xlrd.open_workbook(inEfile)
     #创建索引顺序获取一个工作表
     table = rfile.sheet_by_index(0)
     #其他方式
     #table = rfile.sheets()[0]
     #table = rfile.sheet_by_name(u'Sheet1')
    
     #获取整行,整列的值
     table.row_values(0)
     table.col_values(0)
    
     #获取行数和列数
     nrows = table.nrows - 1
     ncols = table.ncols
    
     #循环获取列表的数据
     #for i in range(nrows):
     #  print table.row_values(i)
     wfile = open(outfile,'w')
     #获取第一列中的所有值
     for i in range(nrows):
       #table.cell(i,0).value获取某一单元格的值
       wfile.write(table.cell(i,0).value.encode('utf8') + '\n')
     wfile.close()

 #将数据写入Excel表
def wExcel(self,infile,outEfile):
     rfile = open(infile,'r')
     buf = rfile.read().split('\n')
     rfile.close()
    
     w = xlwt.Workbook()
     sheet = w.add_sheet('sheet1')
     for i in range(len(buf)):
       print buf[i]
       sheet.write(i,0,buf[i].decode('utf8'))
     w.save(outEfile)

if __name__ == '__main__':
   t = OperExcel()
   t.rExcel('test.xls','test')   t.wExcel('test','1.xls')

本文为个人存档学习,转自http://blog.sina.com.cn/s/blog_6babbcb8010182c3.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值