Python-implemented Excel file read-write class

Source: Internet
Author: User
This article describes the Excel file read-write class implemented by Python. Share to everyone for your reference. Specific as follows:

#coding =utf-8####################################################### #filename: excelrw.py#author:defias#date : 2015-4-27#function:read or write Excel file###################################################### #import Xlrdimport xlwtimport xlutils.copy Import Os.pathclass xlsengine (): "" "The Xlsengine is a class for Excel operation Us Age: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_workbo Ok (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.XL Rd_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_objec T.sheet_names () If SheetName not in Worksheets:print ('%s was not exit. ') %sheetname) return False worksheet = self.xlrd_object.sheet_by_name (sheetname) cell = Worksheet.cel L_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!-check sheetn rown and Coln are right. ') DefReadrow (Self,sheetname= ' Sheet1 ', rown=0): "" "Read file ' s a row content Usage:xlseng.readrow (' SheetName ', row n) "" "try:if self.isopentrue = = True:worksheets = Self.xlrd_object.sheet_names () if SheetName Not in Worksheets:print ('%s was not exit. ') %sheetname) return False worksheet = self.xlrd_object.sheet_by_name (sheetname) row = Worksh Eet.row_values (rown) print (' [file:%s,sheet:%s,row:%s]:%s. '% (self.xls_name,sheetname,rown,row)) ELSE:PR Int (' file%s is not open. ')  %self.xls_name) Except:print (' Readrow is false! * Please check sheetn rown are 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 SHEETN Ame not in Worksheets:print ('%s was not exit. ')        %sheetname) return FalseWorksheet = 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 are right. ')       def Writecell (self,value= ", sheetn=0,rown=0,coln=0):" "" "" Write a cell to File,other cell are 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 are not change Usage:xlseng.writerow (' str1,str2,str3...strn ', sheetn,rown.co LN) "" "try:if self.isopentrue = = TRUE:XLRD_OBJECTC = Xlutils.copy.copy (self.xlrd_object) works Heet = Xlrd_objectc.get_sheet (SHEETN) values = Values.split (', ') for value in Values:worksheet.wri Te (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 are not the change Usa Ge: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,sheetname 2 ... ' "" "" "" "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,c Ell_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:w Orksheets = Self.xlrd_object.sheet_names () XLRD_OBJECTC = Xlutils.copy.copy (self.xlrd_object) Sheetnames = s Heetnames.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_ove      Rwrite_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! ' check. ') "" " def chgsheet (self,sheetn,values): Def Clear (self): "" "if __name__ = = ' __main__ ': #初始化对象 Xlseng = Xlsengine (' E:\\co De\\python\\test2.xls ') #新建文件, you can specify the name of the sheet page you want to create, and the default value of the new Sheet1 #print ("\nxlseng.filecreate ():") #xlseng. Filecreate (' Newesheet1,newesheet2,newesheet3 ') #打开文件 print ("Xlseng. Open (): ") Xlseng.open () #添加sheet页 print (" \nxlseng.addsheet (): ") xlseng.addsheet (' Addsheet1,addsheet2,addsheet3 ') # Output File information print ("\nxlseng.info ():") Xlseng.info () #读取sheet1页第3行第3列单元格数据 (Default read Sheet1 page 1th row 1th column cell data) print ("\ Nxlseng.readcell (): ") Xlseng.readcell (' Sheet1 ', 2,2) #读取sheet1页第2行的数据 (default reads data from the 1th row of the Sheet1 page) print (" \nxlseng.readrow () : ") xlseng.readrow (' Sheet1 ', 1) #读取sheet1页第3列的数据 (default reads data from the 1th column of the Sheet1 page) print (" \nxlseng.readcol (): ") Xlseng.readcol ('  Sheet1 ', 2) #向第一个sheet页的第2行第4列写字符串数据 ' I am writecell writed ' (default writes an empty string to the 1th row 1th column of the first sheet page) print ("\nxlseng.writecell ():") Xlseng.writecell (' I am Writecell writed ', 0,1,3) #向第一个sheet页写一行数据, each column has a value of ' ROWSTR1,ROWSTR2,ROWSTR3 ', starting with the 3rd row 4th column ( By default, a row of data is written to the first sheet page, with a value of ' ', beginning with the 1th column on line 1th, to print ("\nxlseng.writerow ():") xlseng.writerow (' Rowstr1,rowstr2,rowstr3 ',  0,2,3) #向第一个sheet页写一列数据, the value of each row is ' COLSTR1,COLSTR2,COLSTR3,COLSTR4 ', starting with the 4th row 4th column (default to the first sheet page to write a column of data, the value ", starting from the 1th row 1th column to write) Print ("\nxlseng.writecol ():") xlseng.writecol (' Colstr1,colstr2,colstr3,colstr4 ', 0,3,3)

Hopefully this article will help you with Python programming.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.