SoFunction
Updated on 2024-11-13

Python implementation of the Excel file read and write classes

This article is an example of Python implementation of the Excel file read and write classes. Shared for your reference. Specific as follows:

#coding=utf-8
#######################################################
#filename:
#author:defias
#date:2015-4-27
#function:read or write excel file
#######################################################
import xlrd
import xlwt
import  
import 
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
   = False #file open flag
 def open(self):
  """
  open a xls file
  Usage:
   ()
  """
  try:
   self.xlrd_object = xlrd.open_workbook(self.xls_name)
    = True
   print('[%s,%s].'%(,self.xlrd_object))
  except:
    = False
   self.xlrd_object = None
   print('open %s failed.'%self.xls_name)
 def info(self):
  """
  show xls file information
  Usage:
   ()  
  """
  if  == True:
   for sheetname in self.xlrd_object.sheet_names():
    worksheet = self.xlrd_object.sheet_by_name(sheetname)
    print('%s:(%d row,%d col).'%(sheetname,,))
  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:
   ('sheetname',rown,coln)
  """
  try:
   if  == 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:
   ('sheetname',rown)
  """
  try:
   if  == 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:
   ('sheetname',coln)
  """
  try:
   if  == 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:
    ('str',sheetn,rown,coln)
  """
  try:
   if  == True:
    xlrd_objectc = (self.xlrd_object)
    worksheet = xlrd_objectc.get_sheet(sheetn)
    (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:
   ('str1,str2,str3...strn',sheetn,)
  """
  try:
   if  == True:
    xlrd_objectc = (self.xlrd_object)
    worksheet = xlrd_objectc.get_sheet(sheetn)
    values = (',')
    for value in values:
     (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:
   ('str1,str2,str3...',sheetn,)
  """
  try:
   if  == True:
    xlrd_objectc = (self.xlrd_object)
    worksheet = xlrd_objectc.get_sheet(sheetn)
    values = (',')
    for value in values:
     (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 (self.xls_name):
    print('%s is exit.'%self.xls_name)
    return False
   workbook = ()
   sheetnames = (',')
   for sheetname in sheetnames:
    workbook.add_sheet(sheetname,cell_overwrite_ok=True)
   (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  == True:
    worksheets = self.xlrd_object.sheet_names()
    xlrd_objectc = (self.xlrd_object)
    sheetnames = (',')
    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__': 
 # Initialize the object
 xlseng = XlsEngine('E:\\Code\\Python\\')
 # New file, you can specify the new sheet page name, the default value of the new sheet1
 #print("\():")
 #('newesheet1,newesheet2,newesheet3')
 # Open the file
 print("():")
 ()
 # Add sheet page
 print("\():")
 ('addsheet1,addsheet2,addsheet3')
 # Output file information
 print("\():")
 ()
 # Read the data in row 3 and column 3 of sheet 1 (default reads the data in row 1 and column 1 of sheet 1)
 print("\():")
 ('sheet1',2,2)
 # Read the data in row 2 of sheet1 (default reads the data in row 1 of sheet1)
 print("\():")
 ('sheet1',1)
 # Read the data in column 3 of sheet1 (default reads the data in column 1 of sheet1)
 print("\():")
 ('sheet1',2)
 # Write string data 'I am writecell writed' to row 2, column 4 of the first sheet page (default is to write empty string to row 1, column 1 of the first sheet page)
 print("\():")
 ('I am writecell writed',0,1,3)
 # Write a row of data to the first sheet page, the value of each column is 'rowstr1,rowstr2,rowstr3', write from row 3 column 4 (default write a row of data to the first sheet page, the value is '', write from row 1 column 1)
 print("\():")
 ('rowstr1,rowstr2,rowstr3',0,2,3)
 # Write a column of data to the first sheet page, the value of each row is 'colstr1,colstr2,colstr3,colstr4', write from row 4, column 4 (default write a column of data to the first sheet page, the value is '', write from row 1, column 1)
 print("\():")
 ('colstr1,colstr2,colstr3,colstr4',0,3,3)

I hope that what I have described in this article will help you in your Python programming.