ExcelParser.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. # -*- coding:utf-8 -*-
  2. import os, sys, time
  3. import xlrd
  4. import xlwt
  5. import json
  6. # 字典不排序;
  7. from collections import OrderedDict
  8. from xlwt import XFStyle, Pattern
  9. from UIT_treeConstant import TreeConst
  10. from UIT_log import info,debug,error
  11. INFO =True
  12. DEBUG =True
  13. ERROR = True
  14. class CExcelParser():
  15. cls = "CExcelParser"
  16. def __init__(self, xls_path=None,UITree=None):
  17. self.UITree = UITree
  18. if type(xls_path) == str:
  19. xls_path = xls_path.decode('utf-8')
  20. self.xls_path = xls_path
  21. def read_excel(self, path=None):
  22. if path is not None:
  23. # 如果是gbk字符,转utf8
  24. if type(path) == str:
  25. path = path.decode('utf-8')
  26. self.xls_path = path
  27. # 打开文件;
  28. wb = xlrd.open_workbook(filename=self.xls_path)
  29. if wb is None:
  30. return
  31. # 获取所有sheet;
  32. sheet = None
  33. for sh_name in wb.sheet_names():
  34. sheet = wb.sheet_by_name(sh_name)
  35. self.parse_excel(sheet, False)
  36. # print "self.valueParams.values:", self.valueParams.values, type(self.valueParams.values)
  37. # print "self.pathParams.paths:", self.pathParams.paths, type(self.pathParams.paths)
  38. # try:
  39. # print json.dumps(self.pathParams.paths)
  40. # print '\r\n'
  41. # print json.dumps(self.valueParams.values)
  42. # print '\r\n'
  43. # # print self.pathParams.paths,'\r\n', self.valueParams.values
  44. # except Exception, e:
  45. # print e
  46. # endfun
  47. def parse_excel(self, sheet, bpath=True):
  48. # 返回由该行中所有单元格的数据组成的列表
  49. pKeys = sheet.row_values(0)
  50. info(self.cls,"parse_excel","params sheet %s keys: %s"%(sheet.name,str(pKeys)),INFO)
  51. # 逐行表;
  52. parentName = None
  53. if u"Value" == sheet.name:
  54. # 逐行遍历(首行除外);
  55. for i in range(1, sheet.nrows):
  56. rowDict = {}
  57. # 获取每行内容;
  58. oneRow = tuple(sheet.row_values(i))
  59. # 遍历单元格;
  60. for index in range(oneRow.__len__()):
  61. item = oneRow[index]
  62. rowDict[pKeys[index]] = item
  63. if rowDict[TreeConst.Value_Name] is None or rowDict[TreeConst.Value_Name].__len__() < 1:
  64. if parentName is None:
  65. error(self.cls, "parse_excel", "Level %s error row %s:" % (sheet.name, str(oneRow)), ERROR)
  66. break
  67. else:
  68. rowDict[TreeConst.Value_Name] = parentName
  69. self.UITree.valueParams.addOption(rowDict)
  70. elif rowDict[TreeConst.Value_Name].__len__() > 0:
  71. parentName = rowDict[TreeConst.Value_Name]
  72. self.UITree.valueParams.addParent(rowDict)
  73. elif "Dialog" == sheet.name:
  74. self.parsePath(sheet, pKeys, self.UITree.dialogParams)
  75. else: # 路径;
  76. self.parsePath(sheet,pKeys, self.UITree.pathParams)
  77. def parsePath(self, sheet,pKeys, treeParams):
  78. parentName = None
  79. for i in range(1, sheet.nrows):
  80. # 获取每行内容;
  81. oneRow = tuple(sheet.row_values(i))
  82. rowDict = {}
  83. for index in range(oneRow.__len__()):
  84. item = oneRow[index]
  85. rowDict[pKeys[index]] = item
  86. if rowDict[TreeConst.Parent_Name] is None or rowDict[TreeConst.Parent_Name].__len__() < 1:
  87. if parentName is None:
  88. error(self.cls, "parse_excel", "Level %s error row %s:" % (sheet.name, str(oneRow)), ERROR)
  89. break
  90. else:
  91. rowDict[TreeConst.Parent_Name] = parentName
  92. treeParams.addOption(sheet.name, rowDict)
  93. elif rowDict[TreeConst.FLevel_Params[0]].__len__() > 0:
  94. parentName = rowDict[TreeConst.Parent_Name]
  95. treeParams.addParent(sheet.name, rowDict)
  96. # endfun
  97. def saveExcelData(self, checkOptionPathExcelData, repeatOptionList, all_UI_TestLanguagePath):
  98. # 设置字体
  99. font = xlwt.Font()
  100. font.bold = True
  101. # 设置边框
  102. borders = xlwt.Borders()
  103. borders.left = xlwt.Borders.THIN
  104. borders.right = xlwt.Borders.THIN
  105. borders.top = xlwt.Borders.THIN
  106. borders.bottom = xlwt.Borders.THIN
  107. # 设置居中
  108. alignment = xlwt.Alignment()
  109. # alignment.horz = xlwt.Alignment.HORZ_CENTER # 水平方向
  110. alignment.horz = xlwt.Alignment.HORZ_LEFT # 水平方向
  111. alignment.vert = xlwt.Alignment.VERT_TOP # 垂直方向
  112. alignment.wrap = 1
  113. # 设置背景颜色
  114. pattern = xlwt.Pattern()
  115. pattern.pattern = xlwt.Pattern.SOLID_PATTERN
  116. pattern.pattern_fore_colour = 3 # 背景颜色
  117. # 定义不同的excel style
  118. style1 = xlwt.XFStyle()
  119. style1.font = font
  120. style1.borders = borders
  121. style1.alignment = alignment
  122. style2 = xlwt.XFStyle()
  123. style2.borders = borders
  124. style2.alignment = alignment
  125. style = XFStyle()
  126. style.borders = borders
  127. style.alignment = alignment
  128. pattern = Pattern()
  129. pattern.pattern = Pattern.SOLID_PATTERN
  130. pattern.pattern_fore_colour = xlwt.Style.colour_map['red'] # 设置单元格背景色为黄色
  131. style.pattern = pattern
  132. # style_align = xlwt.easyxf('align: wrap on')
  133. if os.path.exists(all_UI_TestLanguagePath):
  134. try:
  135. os.remove(all_UI_TestLanguagePath)
  136. except Exception, e:
  137. print e
  138. return False
  139. # 创建工作簿;
  140. book = xlwt.Workbook(encoding='utf-8')
  141. # 创建sheet;
  142. sheet = book.add_sheet(u'到达Option路径检测', cell_overwrite_ok=True)
  143. # 设置表格自适应宽度的数组
  144. col_width = [2, 25, 15, 120]
  145. # 创建标题行;
  146. row0 = [u'序号', u'Option名称', u'检测到达路径结果', u'到达Option路径']
  147. for i in range(len(row0)):
  148. sheet.write(0, i, row0[i], style=style1)
  149. index = 1
  150. for checkdata in checkOptionPathExcelData:
  151. sheet.write(index, 0, index, style=style2)
  152. for j in range(len(checkdata)):
  153. # 如果结果不为Pass则在表格中标红
  154. if j == 1 and checkdata[j] != 'Pass':
  155. sheet.write(index, j + 1, checkdata[j], style=style)
  156. else:
  157. # if j == 1:
  158. # sheet.write(index, j + 1, checkdata[j], style=style_align)
  159. # else:
  160. sheet.write(index, j + 1, checkdata[j], style=style2)
  161. # if col_width[j] < self.len_byte(checkdata[j]):
  162. # col_width[j] = self.len_byte(checkdata[j])
  163. index += 1
  164. # 设置栏位宽度,栏位宽度小于10时候采用默认宽度
  165. for i in range(len(col_width)):
  166. if col_width[i] > 10:
  167. sheet.col(i).width = 256 * (col_width[i] + 1)
  168. sheet2 = book.add_sheet(u'Option查重', cell_overwrite_ok=True)
  169. # 设置表格自适应宽度的数组
  170. col_width2 = [2, 30, 30]
  171. # 创建标题行;
  172. row02 = [u'序号', u'重复Option名称', u'重复Option在源表格的sheet名称']
  173. for i in range(len(row02)):
  174. sheet2.write(0, i, row02[i], style=style1)
  175. index2 = 1
  176. for repeatOption in repeatOptionList:
  177. sheet2.write(index2, 0, index2, style=style2)
  178. for j in range(len(repeatOption)):
  179. sheet2.write(index2, j + 1, repeatOption[j], style=style2)
  180. index2 += 1
  181. # 设置栏位宽度,栏位宽度小于10时候采用默认宽度
  182. for i in range(len(col_width2)):
  183. if col_width2[i] > 10:
  184. sheet2.col(i).width = 256 * (col_width2[i] + 1)
  185. # 保存xls;
  186. try:
  187. book.save(all_UI_TestLanguagePath)
  188. return True
  189. except Exception, e:
  190. print e
  191. return False
  192. # 新增表格查询接口
  193. # # 获取表格Value层级中,value_name下包含的value列表
  194. # def getSubValueList(self, value_name):
  195. # valueList = []
  196. # if self.valueParams.values.has_key(value_name):
  197. # # print parser.valueParams.values["source"]
  198. # # print parser.valueParams.values["source"]["value"]
  199. # valueDictList = self.valueParams.values[value_name]["value"]
  200. # for valueDict in valueDictList:
  201. # valueList.append(valueDict["value"])
  202. # # print "valueList:", valueList, type(valueList)
  203. # return valueList
  204. if __name__ == "__main__":
  205. # path = r'E:\svn\SAT\项目资料\第四期-推广使用和画面检测\06-设计文档\01-蓝图设计\UiTree3.0方案\MenuTree_MS6586_EU.xls'
  206. # path = r'E:\SAT\resource\MenuTree\MS3663\DVB-T2 panasonic\MenuTree.xls'
  207. # path = r'E:/SAT/resource\MenuTree\MS6586\ATSC\MenuTree.xls'
  208. path = r'E:\SAT\resource\MenuTree\MS6586\ATSC\MenuTree_DVBT.xls'
  209. # path = r'E:\MenuTree.xls'
  210. # path = r'E:\SAT\resource\MenuTree\6586\MS6586_ATSC\MenuTree.xls'
  211. # path = getMenuTree3SelectedProjectCfgPath() + '\\MenuTree.xls'
  212. parser = CExcelParser(path)
  213. parser.read_excel()
  214. dataDict = parser.get_parent_ocr_dict("network")
  215. print "dataDict:", dataDict, type(dataDict)
  216. # parent = "source"
  217. # option = "atv"
  218. # parser.getOptionTextList(parent, option)
  219. # value_name = "source"
  220. # value = "atv"
  221. # parser.getValueTextList(value_name, value)
  222. # SubValueList1 = parser.getSubValueList("source")
  223. # SubValueList2 = parser.getSubValueList("backlight")
  224. # parent = "picture"
  225. # parent = "manual_tuning"
  226. # parser.getSubOptionList(parent)
  227. # optionList = []
  228. # paths = parser.pathParams.paths
  229. #
  230. # for level in paths:
  231. # if paths[level].has_key(parent):
  232. # optionDictList = paths[level][parent]["value"]
  233. # for optionDict in optionDictList:
  234. # optionList.append(optionDict["option"])
  235. # print "optionList:", optionList, type(optionList)
  236. # print parser.get_value("source", "")
  237. # checkOptionPathExcelData = parser.getCheckOptionPathExcelData()
  238. # print "checkOptionPathExcelData:", checkOptionPathExcelData
  239. # repeatOptionList = parser.getRepeatOptionList()
  240. # isSaveExcelTrue = parser.saveExcelData(checkOptionPathExcelData, repeatOptionList,
  241. # r'E:\MenuTree_Check_Option_Result.xls')
  242. # path = r'E:\SAT\resource\MenuTree\6586\MS6586_ATSC\MenuTree.xls'
  243. # path = getMenuTree3SelectedProjectCfgPath() + '\\MenuTree.xls'
  244. # print "isSaveExcelTrue:", isSaveExcelTrue
  245. # valueSheetOptionList = parser.getValueSheetOptionList()
  246. # repeatValueName_ValueSheet = parser.getRepeatValueName_ValueSheet()
  247. # repeatOption_otherSheet = parser.getRepeatOption_otherSheet()
  248. # optionPath, optionPathResult = parser.checkOptionPath("picture_preset11")
  249. # print "optionPath:", optionPath, type(optionPath)
  250. # print "optionPathResult:", optionPathResult, type(optionPathResult)
  251. # optionPath, optionPathResult = parser.checkOptionPath("instant_power_on")
  252. # print "optionPath:", optionPath, type(optionPath)
  253. # print "optionPathResult:", optionPathResult, type(optionPathResult)
  254. # path_params = parser.get_option_paths("picture_preset")
  255. # print "path_params:", path_params, type(path_params)
  256. # print "path_params[0][0]:",path_params[0][0]
  257. # print parser.get_option_paths('picture')
  258. # print parser.get_option('picture')
  259. # print parser.get_value('backlight',10)
  260. # print parser.get_parent_ocr_dict('source_hdmi1')
  261. # print parser.get_parent_ocr_list('channel')
  262. # print parser.get_parent_ocr_dict('channel')
  263. # print parser.get_parent_ocr_dict('other_setting')
  264. # print parser.get_parent_ocr_list('5khz')
  265. # print parser.get_parent_ocr_dict('picture_preset', True)
  266. # print parser.get_pair_values('picture_preset', False)
  267. # print parser.get_pair_values('source')
  268. # print parser.get_ocr_list('Second','picture','picture_preset')
  269. # vp, pp = parser.get_menu_paths("auto_volume_control", "off")
  270. # print vp
  271. # vp, pp = parser.get_menu_paths("picture_preset", "dynamic")
  272. # print vp
  273. # pp = parser.get_option_paths('picture_preset')
  274. # print pp.__len__(), pp[g_level[0]]
  275. # print "\r\nvp:", vp, type(vp)
  276. # print "\r\npp:", pp, type(pp)
  277. # # print json.dumps(pp)
  278. # revpp = reversed(pp)
  279. # for item in revpp:
  280. # print item, pp[item]
  281. # print 'value:\r\n'
  282. # print vp
  283. # # print "revpp:", revpp, type(revpp)