TExcelParser.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 xlsConst import xlsConst as xlsc
  10. from BaseLog import CBaseLog
  11. class CExcelParser(CBaseLog):
  12. def __init__(self, optionExcel, xls_path=None):
  13. CBaseLog.__init__(self)
  14. self.__optionExcel = optionExcel
  15. if type(xls_path) == str:
  16. xls_path = xls_path.decode('utf-8')
  17. self.xls_path = xls_path
  18. def read_excel(self, path=None):
  19. if path is not None:
  20. if type(path) == str:
  21. path = path.decode('utf-8')
  22. self.xls_path = path
  23. if not os.path.exists(self.xls_path):
  24. return
  25. # 打开文件;
  26. wb = xlrd.open_workbook(filename=self.xls_path)
  27. if wb is None:
  28. return
  29. # 获取所有sheet;
  30. sheet = None
  31. for sh_name in wb.sheet_names():
  32. sheet = wb.sheet_by_name(sh_name)
  33. self.parse_excel(sheet, False)
  34. # endfun
  35. def parse_excel(self, sheet, bpath=True):
  36. pKeys = sheet.row_values(0)
  37. self.info(u"params sheet %s keys: %s" % (sheet.name, str(pKeys)))
  38. parentName = None
  39. if u"Value" == sheet.name:
  40. for i in range(1, sheet.nrows):
  41. # 获取每行内容;
  42. oneRow = tuple(sheet.row_values(i))
  43. rowDict = {}
  44. for index in range(oneRow.__len__()):
  45. item = oneRow[index]
  46. if pKeys[index] == "toparent_key" and oneRow[index] != "":
  47. rowDict[pKeys[index]] = self.__parseToParentKey(item)
  48. elif pKeys[index] == "layout" and oneRow[index] != "":
  49. rowDict[pKeys[index]] = self.__parseLayout(item)
  50. else:
  51. rowDict[pKeys[index]] = item
  52. if rowDict[xlsc.value_name] is None or rowDict[xlsc.value_name].__len__() < 1:
  53. if parentName is None:
  54. self.error(u"Level %s error row %s:" % (sheet.name, str(oneRow)))
  55. break
  56. else:
  57. rowDict[xlsc.value_name] = parentName
  58. self.__optionExcel.valueParams.addOption(rowDict)
  59. elif rowDict[xlsc.value_name].__len__() > 0:
  60. parentName = rowDict[xlsc.value_name]
  61. self.__optionExcel.valueParams.addParent(rowDict)
  62. elif "Dialog" == sheet.name:
  63. self.parsePath(sheet, pKeys, self.__optionExcel.dialogParams)
  64. else: # 路径;
  65. self.parsePath(sheet, pKeys, self.__optionExcel.pathParams)
  66. def parsePath(self, sheet, pKeys, treeParams):
  67. parentName = None
  68. for i in range(1, sheet.nrows):
  69. # 获取每行内容;
  70. oneRow = tuple(sheet.row_values(i))
  71. rowDict = {}
  72. for index in range(oneRow.__len__()):
  73. item = oneRow[index]
  74. if pKeys[index] == "toparent_key" and oneRow[index] != "":
  75. rowDict[pKeys[index]] = self.__parseToParentKey(item)
  76. elif pKeys[index] == "layout" and oneRow[index] != "":
  77. rowDict[pKeys[index]] = self.__parseLayout(item)
  78. else:
  79. rowDict[pKeys[index]] = item
  80. if rowDict[xlsc.parent] is None or rowDict[xlsc.parent].__len__() < 1:
  81. if parentName is None:
  82. self.error(u"Level %s error row %s:" % (sheet.name, str(oneRow)))
  83. continue
  84. else:
  85. rowDict[xlsc.parent] = parentName
  86. treeParams.addOption(sheet.name, rowDict)
  87. elif rowDict[xlsc.FLevel_Params[0]].__len__() > 0:
  88. parentName = rowDict[xlsc.parent]
  89. treeParams.addParent(sheet.name, rowDict)
  90. # endfun
  91. def saveExcelData(self, checkOptionPathExcelData, repeatOptionList, all_UI_TestLanguagePath):
  92. # 设置字体
  93. font = xlwt.Font()
  94. font.bold = True
  95. # 设置边框
  96. borders = xlwt.Borders()
  97. borders.left = xlwt.Borders.THIN
  98. borders.right = xlwt.Borders.THIN
  99. borders.top = xlwt.Borders.THIN
  100. borders.bottom = xlwt.Borders.THIN
  101. # 设置居中
  102. alignment = xlwt.Alignment()
  103. # alignment.horz = xlwt.Alignment.HORZ_CENTER # 水平方向
  104. alignment.horz = xlwt.Alignment.HORZ_LEFT # 水平方向
  105. alignment.vert = xlwt.Alignment.VERT_TOP # 垂直方向
  106. alignment.wrap = 1
  107. # 设置背景颜色
  108. pattern = xlwt.Pattern()
  109. pattern.pattern = xlwt.Pattern.SOLID_PATTERN
  110. pattern.pattern_fore_colour = 3 # 背景颜色
  111. # 定义不同的excel style
  112. style1 = xlwt.XFStyle()
  113. style1.font = font
  114. style1.borders = borders
  115. style1.alignment = alignment
  116. style2 = xlwt.XFStyle()
  117. style2.borders = borders
  118. style2.alignment = alignment
  119. style = XFStyle()
  120. style.borders = borders
  121. style.alignment = alignment
  122. pattern = Pattern()
  123. pattern.pattern = Pattern.SOLID_PATTERN
  124. pattern.pattern_fore_colour = xlwt.Style.colour_map['red'] # 设置单元格背景色为黄色
  125. style.pattern = pattern
  126. # style_align = xlwt.easyxf('align: wrap on')
  127. if os.path.exists(all_UI_TestLanguagePath):
  128. try:
  129. os.remove(all_UI_TestLanguagePath)
  130. except Exception, e:
  131. print e
  132. return False
  133. # 创建工作簿;
  134. book = xlwt.Workbook(encoding='utf-8')
  135. # 创建sheet;
  136. sheet = book.add_sheet(u'到达Option路径检测', cell_overwrite_ok=True)
  137. # 设置表格自适应宽度的数组
  138. col_width = [2, 25, 15, 120]
  139. # 创建标题行;
  140. row0 = [u'序号', u'Option名称', u'检测到达路径结果', u'到达Option路径']
  141. for i in range(len(row0)):
  142. sheet.write(0, i, row0[i], style=style1)
  143. index = 1
  144. for checkdata in checkOptionPathExcelData:
  145. sheet.write(index, 0, index, style=style2)
  146. for j in range(len(checkdata)):
  147. # 如果结果不为Pass则在表格中标红
  148. if j == 1 and checkdata[j] != 'Pass':
  149. sheet.write(index, j + 1, checkdata[j], style=style)
  150. else:
  151. # if j == 1:
  152. # sheet.write(index, j + 1, checkdata[j], style=style_align)
  153. # else:
  154. sheet.write(index, j + 1, checkdata[j], style=style2)
  155. # if col_width[j] < self.len_byte(checkdata[j]):
  156. # col_width[j] = self.len_byte(checkdata[j])
  157. index += 1
  158. # 设置栏位宽度,栏位宽度小于10时候采用默认宽度
  159. for i in range(len(col_width)):
  160. if col_width[i] > 10:
  161. sheet.col(i).width = 256 * (col_width[i] + 1)
  162. sheet2 = book.add_sheet(u'Option查重', cell_overwrite_ok=True)
  163. # 设置表格自适应宽度的数组
  164. col_width2 = [2, 30, 30]
  165. # 创建标题行;
  166. row02 = [u'序号', u'重复Option名称', u'重复Option在源表格的sheet名称']
  167. for i in range(len(row02)):
  168. sheet2.write(0, i, row02[i], style=style1)
  169. index2 = 1
  170. for repeatOption in repeatOptionList:
  171. sheet2.write(index2, 0, index2, style=style2)
  172. for j in range(len(repeatOption)):
  173. sheet2.write(index2, j + 1, repeatOption[j], style=style2)
  174. index2 += 1
  175. # 设置栏位宽度,栏位宽度小于10时候采用默认宽度
  176. for i in range(len(col_width2)):
  177. if col_width2[i] > 10:
  178. sheet2.col(i).width = 256 * (col_width2[i] + 1)
  179. # 保存xls;
  180. try:
  181. book.save(all_UI_TestLanguagePath)
  182. return True
  183. except Exception, e:
  184. print e
  185. return False
  186. # 新增表格查询接口
  187. # # 获取表格Value层级中,value_name下包含的value列表
  188. # def getSubValueList(self, value_name):
  189. # valueList = []
  190. # if self.valueParams.values.has_key(value_name):
  191. # # print parser.valueParams.values["source"]
  192. # # print parser.valueParams.values["source"]["value"]
  193. # valueDictList = self.valueParams.values[value_name]["value"]
  194. # for valueDict in valueDictList:
  195. # valueList.append(valueDict["value"])
  196. # # print "valueList:", valueList, type(valueList)
  197. # return valueList
  198. def __parseToParentKey(self, keyStr):
  199. keyList = ["key", "duration", "wait", "tolevel", "dialog"]
  200. # 按照"key[]"的方式切片并解析成字典
  201. keyDict = self.__parseMulParam(keyList, keyStr)
  202. return keyDict
  203. def __parseLayout(self, layoutStr):
  204. keyList = ["bounds"]
  205. keyDict = self.__parseMulParam(keyList, layoutStr)
  206. keyDict["bounds"] = tuple(keyDict["bounds"].split(","))
  207. return keyDict
  208. '''
  209. 返回:{key:value,key2:value2,...}
  210. '''
  211. def __parseMulParam(self, keyList, params):
  212. paramDict = {}
  213. for key in keyList:
  214. value = self.__parseParam(key, params)
  215. paramDict[key] = value
  216. return paramDict
  217. '''
  218. char为该项参数的括符符号,必须成对带入。默认为中括号[]
  219. '''
  220. #将数据从excel表格里取出来,只返回括号里面的内容
  221. def __parseParam(self, key, params, char="[]"):
  222. # 为防止key在其他地方存在相同关键字,添加一个"["做区别
  223. key1 = key + char[0]
  224. keyIndex = params.find(key1)
  225. if keyIndex == -1:
  226. return ""
  227. # key.__len__()-1 为去掉"["的处理
  228. str1 = params[keyIndex + key1.__len__()-1:params.__len__()]
  229. i1 = str1.find(char[0])
  230. i2 = str1.find(char[1])
  231. if i1 == -1 or i2 == -1:
  232. return ""
  233. str2 = str1[i1 + 1: i2]
  234. return str2.strip()
  235. if __name__ == "__main__":
  236. pass