[置顶] Python处理Excel(三):内置数据类型处理Excel数据

经过了一段时间理论知识的学习和几个demo练手后,开始了这个略微复杂的项目。项目需要读取一个EXCEL中两个sheet中的数据,一个sheet中包含公式,另一个sheet包含公式中的变量的值,将它们分们别类的读出后写入当前EXCEL中的新建的sheet中。

在完成这个项目前,我阅读并学习了如下资料:

  • Python基础教程 Mafnus Lie Hetland著
  • Python文档 https://docs.python.org/2/index.html
  • xlrd xlwt文档 pdf 需要可私信

这篇文章的程序可以实现功能,但不一定高效且最优,所以文章的目的不是提供一个完整的程序,而是记录在编写程序的过程中遇到的问题已经解决问题的思路和方法。对自己在当时遇到的一些变成难点进行记录和理论补充。

程序如下:

class readexcel:

	def __init__(self,filename='scenario.xls'):
		self.__filename=filename
		self.__book=xlrd.open_workbook(filename,formatting_info=True)
		self.__sheetnames=[]#sheet名字		
		self.__Key=[]#存储全局键值对
		self.__Value=[]				
		self.__form={}				
		self.__ip=[]
		self.__ip_pos=[]
		self.__ip_fst={}
		self.__mode=[]					
		self.__paramName=[]
		self.__formula=[]		
		self.__Scen={}
		self.__VPparam=[]
		self.__VPperiod=[]
		self.__VRparam=[]
		self.__VRperiod=[]		
				
		self.__CONFdict={}#config参数表		
		self.__BWdict={}#BW参数表

这里需要注意四点

1.作用域

  • python中只有class def lamda可以改变变量的作用域。一个类定义确定了一个名字空间,位于类体里面的定义都局部于这个类体,这些局部名字在该类之外不能直接看到,也不会与外面的名字冲突。在执行一个类定义时,将以该类为作用域创建一个新的名字空间。类定义里的所有语句都在这个局部名字空间里产生效果。这样创建的类名字空间将一直存在,除非明确删除。
  • 而诸如if/elif/else、try/except/finally、for/while和在C语言中不同,其在python中并不具有更改作用域的功能。代码块里面的变量再外面依然可以正常访问。

2.类的属性名

  • 程序中不需要说明对象有那些属性,赋值时自动创建,同变量
  • 在一个类定义中,所有特殊的名字都以两个下划线开始,并以两个下划线结束,如__init__() __add__()'+' __ne___()'!='
  • 在一个类定义中,由下划线_开头的属性名和函数名都当作内部名字使用,不应该在这个类之外使用
  • 在一个类定义中,由两个下划线__开头,但不以两个下划线结尾的名字,在类定义之外不能直接使用这个名字访问

3.类的方法

  • 实例方法:操作本类对象实例的方法,在函数参数表中第一个参数表示实际使用时的调用对象,通常以self作为参数名
  • 静态方法:描述时需要在函数定义的头部行之前加修饰符@staticmethod

4.formatting_info=True

  • 该选项默认为False,设位True可以保留Excel的格式信息


for i in self.__book__.sheet_names():
			if i.lower()=='config'or i.lower()=='bw':
				
				sheet=self.__book__.sheet_by_name(i)
				count=1
				for row in range(0,sheet.nrows):
					for col in range(0,sheet.ncols):
		                ###-----------读取config参数---------------------------
						#-------读取变量定位符project...
						if sheet.cell_type(row,col)==xlrd.XL_CELL_TEXT and\
						   sheet.cell_value(row,col).lower()=='project':
							self.__CONFdict__.setdefault('Project',\
							sheet.cell_value(row,col+1))
						elif sheet.cell_type(row,col)==xlrd.XL_CELL_TEXT and\
						     sheet.cell_value(row,col).lower()=='#key':

这段代码需要注意 四点

1.xlrd.Book类

  • nsheets----->sheet_by_index(sheet index)
  • sheet_names---->sheet_by_name(sheet name)
  • sheets

2.xlrd.Sheet类

  • name
  • nrows
  • ncols
  • row(row index)
  • col(col index)
  • row_types(start index,optional end index)
  • col_types(start index,optional end index)
  • row_slice(start index,optional end index)
  • col_slice(start index,optional end index)

3.xlrd.Sheet.Cell类

  • value=sheet.cell_value
  • ctype=sheet.cell_type

4.Cell Type

  • Text:xlrd.XL_CELL_TEXT
  • Number:xlrd.XL_CELL_NUMBER
  • Date: xlrd.XL_CELL_DATE
  • Booleanxlrd.XL_CELL_BOOLEAN
  • Errorxlrd.XL_CELL_ERROR
  • Empty/Blank

             xlrd.XL_CELL_EMPTY
             xlrd.XL_CELL_BLANK


self.__Wbook__=copy(self.__book__)
		
		xlwt.add_palette_colour('style1',22)
		self.__Wbook__.set_colour_RGB(22,189,183,107)
		xlwt.add_palette_colour('style2',23)
		self.__Wbook__.set_colour_RGB(23,25,25,112)
		xlwt.add_palette_colour('style3',24)
		self.__Wbook__.set_colour_RGB(24,240,230,140)
		style1 = xlwt.easyxf('pattern: pattern solid, fore_colour style1,back_colour black;'
					      'font: colour style2, bold True;'
						'borders: left 0x0d , right 0x0d, top 0x0d, bottom 0x0d;'
						'alignment: horz center,vert center')
		style2 = xlwt.easyxf(
					      'font: colour style2, bold False;'
						'borders: left 0x0d,left_colour black , right 0x0d, top 0x0d, bottom 0x0d;'
						'alignment: horz center,vert center')
		style3 = xlwt.easyxf('pattern: pattern solid, fore_colour style3,back_colour black;'
					      'font: colour style2, bold True;'
						'borders: left 0x0d , right 0x0d, top 0x0d, bottom 0x0d;'
						'alignment: horz center,vert center')

这个段代码需要注意 两点

1.xlutils.copy

这么模块可以把xlrd.Book转化为xlwt.Workbook。这个功能再需要更新一个已经存在的文件上是非常有用的。

self.__Wbook__=copy(self.__book__)
2.add_palette_colour('name',index)

自定义一种颜色的调色板,第一个参数这个调色板的名字,第二个是个颜色在调色板中的序号,第二参数不能取21以下的值,否则会覆盖掉系统默认的颜色,造成文件着色异常。

通过set_colour为调色板选定一个颜色


sheet.write_merge(1,num+2,0,0,self.__CONFdict__['Project']+\
				          '\n estimate \nBW(MB/s)',style2)
			sheet.write_merge(1,num+2,4,4,self.__CONFdict__['Project']+\
   				   	  '\n simulation \nBW(MB/s)',style2)

  • write_merge(row,row+h,col,col+w,string,style)



你可能感兴趣的:(python,数据,Excel,结构,methods)