TExcelParser.py 11 KB

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