Python实现的Excel文件读写类


Posted in Python onJuly 30, 2015

本文实例讲述了Python实现的Excel文件读写类。分享给大家供大家参考。具体如下:

#coding=utf-8
#######################################################
#filename:ExcelRW.py
#author:defias
#date:2015-4-27
#function:read or write excel file
#######################################################
import xlrd
import xlwt
import xlutils.copy 
import os.path
class XlsEngine():
 """
 The XlsEngine is a class for excel operation
 Usage: 
  xlseng = XlsEngine('filePath') 
 """
 def __init__(self,xlsname):
  """
  define class variable
  """
  self.xls_name = xlsname #file name
  self.xlrd_object = None #workbook object
  self.isopentrue = False #file open flag
 def open(self):
  """
  open a xls file
  Usage:
   xlseng.open()
  """
  try:
   self.xlrd_object = xlrd.open_workbook(self.xls_name)
   self.isopentrue = True
   print('[%s,%s].'%(self.isopentrue,self.xlrd_object))
  except:
   self.isopentrue = False
   self.xlrd_object = None
   print('open %s failed.'%self.xls_name)
 def info(self):
  """
  show xls file information
  Usage:
   xlseng.info()  
  """
  if self.isopentrue == True:
   for sheetname in self.xlrd_object.sheet_names():
    worksheet = self.xlrd_object.sheet_by_name(sheetname)
    print('%s:(%d row,%d col).'%(sheetname,worksheet.nrows,worksheet.ncols))
  else:
   print('file %s is not open.'%self.xls_name)
 def readcell(self,sheetname='sheet1',rown=0,coln=0):
  """
  read file's a cell content
  Usage:
   xlseng.readcell('sheetname',rown,coln)
  """
  try:
   if self.isopentrue == True:
    worksheets = self.xlrd_object.sheet_names()
    if sheetname not in worksheets:
     print('%s is not exit.'%sheetname)
     return False
    worksheet = self.xlrd_object.sheet_by_name(sheetname)
    cell = worksheet.cell_value(rown,coln)
    print('[file:%s,sheet:%s,row:%s,col:%s]:%s.'%(self.xls_name,sheetname,rown,coln,cell))
   else:
    print('file %s is not open.'%self.xls_name)
  except:
   print('readcell is false! please check sheetn rown and coln is right.')
 def readrow(self,sheetname='sheet1',rown=0):
  """
  read file's a row content
  Usage:
   xlseng.readrow('sheetname',rown)
  """
  try:
   if self.isopentrue == True:
    worksheets = self.xlrd_object.sheet_names()
    if sheetname not in worksheets:
     print('%s is not exit.'%sheetname)
     return False    
    worksheet = self.xlrd_object.sheet_by_name(sheetname)
    row = worksheet.row_values(rown)
    print('[file:%s,sheet:%s,row:%s]:%s.'%(self.xls_name,sheetname,rown,row))
   else:
    print('file %s is not open.'%self.xls_name)
  except:
   print('readrow is false! please check sheetn rown is right.')
 def readcol(self,sheetname='sheet1',coln=0):
  """
  read file's a col content
  Usage:
   xlseng.readcol('sheetname',coln)
  """
  try:
   if self.isopentrue == True:
    worksheets = self.xlrd_object.sheet_names()
    if sheetname not in worksheets:
     print('%s is not exit.'%sheetname)
     return False
    worksheet = self.xlrd_object.sheet_by_name(sheetname)
    col = worksheet.col_values(coln)
    print('[file:%s,sheet:%s,col:%s]:%s.'%(self.xls_name,sheetname,coln,col))
   else:
    print('file %s is not open.'%self.xls_name)
  except:
   print('readcol is false! please check sheetn coln is right.')
 def writecell(self,value='',sheetn=0,rown=0,coln=0):
  """
  write a cell to file,other cell is not change
  Usage:
    xlseng.writecell('str',sheetn,rown,coln)
  """
  try:
   if self.isopentrue == True:
    xlrd_objectc = xlutils.copy.copy(self.xlrd_object)
    worksheet = xlrd_objectc.get_sheet(sheetn)
    worksheet.write(rown,coln,value)
    xlrd_objectc.save(self.xls_name)
    print('writecell value:%s to [sheet:%s,row:%s,col:%s] is ture.'%(value,sheetn,rown,coln))
   else:
    print('file %s is not open.'%self.xls_name)
  except:
   print('writecell is false! please check.')
 def writerow(self,values='',sheetn=0,rown=0,coln=0):
  """
  write a row to file,other row and cell is not change
  Usage:
   xlseng.writerow('str1,str2,str3...strn',sheetn,rown.coln)
  """
  try:
   if self.isopentrue == True:
    xlrd_objectc = xlutils.copy.copy(self.xlrd_object)
    worksheet = xlrd_objectc.get_sheet(sheetn)
    values = values.split(',')
    for value in values:
     worksheet.write(rown,coln,value)
     coln += 1
    xlrd_objectc.save(self.xls_name)
    print('writerow values:%s to [sheet:%s,row:%s,col:%s] is ture.'%(values,sheetn,rown,coln))
   else:
    print('file %s is not open.'%self.xls_name)
  except:
   print('writerow is false! please check.')
 def writecol(self,values='',sheetn=0,rown=0,coln=0):
  """
  write a col to file,other col and cell is not change
  Usage:
   xlseng.writecol('str1,str2,str3...',sheetn,rown.coln)
  """
  try:
   if self.isopentrue == True:
    xlrd_objectc = xlutils.copy.copy(self.xlrd_object)
    worksheet = xlrd_objectc.get_sheet(sheetn)
    values = values.split(',')
    for value in values:
     worksheet.write(rown,coln,value)
     rown += 1
    xlrd_objectc.save(self.xls_name)
    print('writecol values:%s to [sheet:%s,row:%s,col:%s] is ture.'%(values,sheetn,rown,coln))
   else:
    print('file %s is not open.'%self.xls_name)
  except:
   print('writecol is false! please check.')
 def filecreate(self,sheetnames='sheet1'):
  """
  create a empty xlsfile
  Usage:
   filecreate('sheetname1,sheetname2...')
  """
  try:
   if os.path.isfile(self.xls_name):
    print('%s is exit.'%self.xls_name)
    return False
   workbook = xlwt.Workbook()
   sheetnames = sheetnames.split(',')
   for sheetname in sheetnames:
    workbook.add_sheet(sheetname,cell_overwrite_ok=True)
   workbook.save(self.xls_name)
   print('%s is created.'%self.xls_name)
  except:
   print('filerator is false! please check.')
 def addsheet(self,sheetnames='sheet1'):
  """
  add sheets to a exit xlsfile
  Usage:
   addsheet('sheetname1,sheetname2...')
  """
  try:
   if self.isopentrue == True:
    worksheets = self.xlrd_object.sheet_names()
    xlrd_objectc = xlutils.copy.copy(self.xlrd_object)
    sheetnames = sheetnames.split(',')
    for sheetname in sheetnames:
     if sheetname in worksheets:
      print('%s is exit.'%sheetname)
      return False
    for sheetname in sheetnames:
     xlrd_objectc.add_sheet(sheetname,cell_overwrite_ok=True)
    xlrd_objectc.save(self.xls_name)
    print('addsheet is ture.')
   else:
    print("file %s is not open \n"%self.xls_name)
  except:
   print('addsheet is false! please check.')
"""
  def chgsheet(self,sheetn,values):
  def clear(self):
""" 
if __name__ == '__main__': 
 #初始化对象
 xlseng = XlsEngine('E:\\Code\\Python\\test2.xls')
 #新建文件,可以指定要新建的sheet页面名称,默认值新建sheet1
 #print("\nxlseng.filecreate():")
 #xlseng.filecreate('newesheet1,newesheet2,newesheet3')
 #打开文件
 print("xlseng.open():")
 xlseng.open()
 #添加sheet页
 print("\nxlseng.addsheet():")
 xlseng.addsheet('addsheet1,addsheet2,addsheet3')
 #输出文件信息
 print("\nxlseng.info():")
 xlseng.info()
 #读取sheet1页第3行第3列单元格数据(默认读取sheet1页第1行第1列单元格数据)
 print("\nxlseng.readcell():")
 xlseng.readcell('sheet1',2,2)
 #读取sheet1页第2行的数据(默认读取sheet1页第1行的数据)
 print("\nxlseng.readrow():")
 xlseng.readrow('sheet1',1)
 #读取sheet1页第3列的数据(默认读取sheet1页第1列的数据)
 print("\nxlseng.readcol():")
 xlseng.readcol('sheet1',2)
 #向第一个sheet页的第2行第4列写字符串数据‘I am writecell writed'(默认向第一个sheet页的第1行第1列写空字符串)
 print("\nxlseng.writecell():")
 xlseng.writecell('I am writecell writed',0,1,3)
 #向第一个sheet页写一行数据,各列的值为‘rowstr1,rowstr2,rowstr3',从第3行第4列开始写入(默认向第一个sheet页写一行数据,值为‘',从第1行第1列开始写入)
 print("\nxlseng.writerow():")
 xlseng.writerow('rowstr1,rowstr2,rowstr3',0,2,3)
 #向第一个sheet页写一列数据,各行的值为‘colstr1,colstr2,colstr3,colstr4',从第4行第4列开始写入(默认向第一个sheet页写一列数据,值为‘',从第1行第1列开始写入)
 print("\nxlseng.writecol():")
 xlseng.writecol('colstr1,colstr2,colstr3,colstr4',0,3,3)

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python妙用之编码的转换详解
Apr 21 Python
python里使用正则表达式的组嵌套实例详解
Oct 24 Python
django数据库migrate失败的解决方法解析
Feb 08 Python
PyQt5每天必学之像素图控件QPixmap
Apr 19 Python
python使用matplotlib库生成随机漫步图
Aug 27 Python
Mac下Anaconda的安装和使用教程
Nov 29 Python
浅谈python下tiff图像的读取和保存方法
Dec 04 Python
pyqt5实现登录界面的模板
May 30 Python
详解python函数的闭包问题(内部函数与外部函数详述)
May 17 Python
python读写配置文件操作示例
Jul 03 Python
使用Python爬虫库requests发送表单数据和JSON数据
Jan 25 Python
python统计文章中单词出现次数实例
Feb 27 Python
Djang中静态文件配置方法
Jul 30 #Python
Python实现根据IP地址和子网掩码算出网段的方法
Jul 30 #Python
Python实现配置文件备份的方法
Jul 30 #Python
Python统计文件中去重后uuid个数的方法
Jul 30 #Python
Python利用正则表达式匹配并截取指定子串及去重的方法
Jul 30 #Python
Python实现简单拆分PDF文件的方法
Jul 30 #Python
使用Python脚本生成随机IP的简单方法
Jul 30 #Python
You might like
PHP数组的交集array_intersect(),array_intersect_assoc(),array_inter_key()函数的小问题
2011/05/29 PHP
phpstudy的php版本自由修改的方法
2017/10/18 PHP
php实现的生成排列算法示例
2019/07/25 PHP
jQuery+jqmodal弹出窗口实现代码分明
2010/06/14 Javascript
js自定义事件及事件交互原理概述(一)
2013/02/01 Javascript
document.documentElement的一些使用技巧
2013/04/18 Javascript
详解addEventListener的三个参数之useCapture
2015/03/16 Javascript
javascript函数特点实例分析
2015/05/14 Javascript
javaScript中Math()函数注意事项
2015/06/18 Javascript
jquery实现带渐变淡入淡出并向右依次展开的多级菜单效果实例
2015/08/22 Javascript
jquery实现的V字形显示效果代码
2015/10/27 Javascript
JS实现上下左右对称的九九乘法表
2016/02/22 Javascript
详解Matlab中 sort 函数用法
2016/03/20 Javascript
全面解析Bootstrap中tab(选项卡)的使用方法
2016/06/06 Javascript
JS实现控制文本框的内容
2016/07/10 Javascript
JavaScript 动态三角函数实例详解
2017/01/08 Javascript
详解闭包解决jQuery中AJAX的外部变量问题
2017/02/22 Javascript
详解JS实现简单的时分秒倒计时代码
2019/04/25 Javascript
解决Python2.7读写文件中的中文乱码问题
2018/04/12 Python
Python中的heapq模块源码详析
2019/01/08 Python
python异步存储数据详解
2019/03/19 Python
Python如何将函数值赋给变量
2020/04/28 Python
Python3爬虫发送请求的知识点实例
2020/07/30 Python
吃透移动端 Html5 响应式布局
2019/12/16 HTML / CSS
珍爱生命演讲稿
2014/05/10 职场文书
小学生国庆节演讲稿
2014/09/05 职场文书
2014年保育员工作总结
2014/12/02 职场文书
中秋客户感谢信
2015/01/22 职场文书
物业工程部主管岗位职责
2015/04/16 职场文书
《酸的和甜的》教学反思
2016/02/18 职场文书
MySQL中utf8mb4排序规则示例
2021/08/02 MySQL
【js设计模式】SOLID五大设计原则
2022/03/24 Javascript
Win11怎么修改电源模式?Win11修改电源模式的方法
2022/04/05 数码科技
jdbc中自带MySQL 连接池实践示例
2022/07/23 MySQL
MySQL生成千万测试数据以及遇到的问题
2022/08/05 MySQL
Springboot集成kafka高级应用实战分享
2022/08/14 Java/Android