您的位置:首页 > 编程语言 > Python开发

Python处理excel数据

2016-08-23 13:02 363 查看
目录

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

B 从Excel中读取数据

C Writing Excel Files

D 稍微复杂的例子和巩固

E 实战

参考文献

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

每一个Excel数据文件从上至下分为三个层级的对象

workbook: 每一个Excel文件就是一个workbook

sheet: 每一个workbook中可以包含多个sheet,具体就对应Excel中我们在左下脚所看到的“sheet1”,“sheet2”等

cell: 每一个sheet就是我们通常所看到的一个表格,可以含有m行,n列,每个确定的行号,列号所对应的一个格子就是一个cell

B 从Excel中读取数据

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

打开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对象实例列表


打开所需的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对象的序列


获取对应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)这样设置的时候


一个读取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模块


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

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


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”)


Rows and Columns 行与列的表示:

row1 = sheet1.row(1)
col0=sheet2.col(0)


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')


svave 保存文件:

wb.save(“zc.xls”)


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')


E 实战

# -*- coding: utf-8 -*-
"""
Created on Tue Aug 23 10:40:56 2016
@author: Dikea
"""
import xlrd
from xlwt import Workbook
#读入excel表
book  = xlrd.open_workbook("50ETF.xlsx")
sh = book.sheet_by_index(0)
#新建一个excel表
book = Workbook()
sheet1 = book.add_sheet('Sheet 1', cell_overwrite_ok=True)  #添加一个sheet
row = 1
cnt = 1
i = 1
while i < sh.nrows:
#判断是否读到最后一行,读入value值为空,即是最后一行
if sh.cell(i, 0).value == '':
break
#判断左右的日期时间是否相等
while sh.cell(i, 0).value < sh.cell(row, 2).value:
i = i + 1
while sh.cell(i, 0).value > sh.cell(row, 2).value:
row = row + 1
#写入新建的excel表
for k in range(0, 4):
if k < 2:
sheet1.write(cnt, k, sh.cell(i, k).value)
else:
sheet1.write(cnt, k, sh.cell(row, k).value)
i = i + 1
cnt = cnt + 1

#保存新建的excel表
book.save('DataAfterDeal.xls')


参考文献

Python读取和写入Excel文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python