经过了一段时间理论知识的学习和几个demo练手后,开始了这个略微复杂的项目。项目需要读取一个EXCEL中两个sheet中的数据,一个sheet中包含公式,另一个sheet包含公式中的变量的值,将它们分们别类的读出后写入当前EXCEL中的新建的sheet中。
在完成这个项目前,我阅读并学习了如下资料:
这篇文章的程序可以实现功能,但不一定高效且最优,所以文章的目的不是提供一个完整的程序,而是记录在编写程序的过程中遇到的问题已经解决问题的思路和方法。对自己在当时遇到的一些变成难点进行记录和理论补充。
程序如下:
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.作用域
2.类的属性名
3.类的方法
4.formatting_info=True
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类
2.xlrd.Sheet类
3.xlrd.Sheet.Cell类
4.Cell Type
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)