Ei kuvausta

excel.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. from openpyxl import load_workbook
  2. import pyodbc
  3. import time
  4. import sys
  5. from pprint import pprint
  6. import datetime
  7. from openpyxl.styles import NamedStyle, Font
  8. from copy import deepcopy
  9. from openpyxl.chart import LineChart, Reference, Series
  10. from openpyxl.chart.text import RichText
  11. from openpyxl.drawing.text import RichTextProperties,Paragraph,ParagraphProperties, CharacterProperties
  12. dateStyle = NamedStyle(name='custom_datetime', number_format='DD/MM/YYYY HH:MM:MM')
  13. # Specifying the ODBC driver, server name, database, etc. directly
  14. #cnxn = None
  15. #cursor = None
  16. '''cursor.execute('select * from data_wb')
  17. rows = cursor.fetchall()
  18. for row in rows:
  19. print(row)'''
  20. wb = load_workbook(filename = './datacpmaster2.xlsx')
  21. #wb.save(filename = './createfrompy.xlsx');
  22. def findCustomer(code):
  23. global cursor
  24. global env
  25. tempResult = []
  26. views = []
  27. if env == "prod":
  28. views = ["bel_master_view", "e_master_view", "mg_master_view", "v_master_view"]
  29. else:
  30. views = ["bel_master_view_dev", "e_master_view_dev", "mg_master_view_dev", "v_master_view_dev"]
  31. ts = []
  32. select = "distinct MI24 as unbStd, PRO1C as customer, cast(PRO8 as varchar) + ' ' + cast(PRO9 as varchar) + cast(PRO10 as varchar) + 'x' + cast(PRO11 as varchar ) + 'x' + cast(PRO12 as varchar) as sizestring, cast(PRO13 as varchar) + ' ' + cast(PRO14 as varchar) + ' ' + cast(PRO15 as varchar) + ' ' + cast(PRO16 as varchar) + ' ' + cast(PRO17 as varchar) + ' ' + cast(PRO18 as varchar) as spec"
  33. where = "PRO1 = '{0}'".format(code)
  34. for v in views:
  35. sqlQuery = "select {0} from {1} where {2}".format(select, v, where)
  36. ts.append(sqlQuery)
  37. merged = []
  38. for t in ts:
  39. merged += cursor.execute(t)
  40. return merged
  41. def createWS(name, values, codeno, filters):
  42. global wb
  43. #wb.create_sheet(name)
  44. wo = wb['Data Cp']
  45. ws = wb.copy_worksheet(wo)
  46. ws.title = name
  47. cust = findCustomer(codeno.replace("-", ""))
  48. ws["B2"] = cust[0].customer
  49. ws["B3"] = codeno.replace("-", "")
  50. ws["B4"] = cust[0].sizestring
  51. ws["B5"] = cust[0].spec
  52. bcode = ord('B')
  53. ccode = 2
  54. for idx, val in enumerate(values):
  55. #print(idx)
  56. c = chr(bcode + idx)
  57. #print(val.lot_no)
  58. if ( bcode + idx) > ord('Z'):
  59. r = bcode + idx - ord('Z')
  60. c = 'A' + chr(ord('A') + (r - 1))
  61. #print("c = "+c)
  62. ws.cell(column= ccode, row=45, value = val.lot_no)
  63. ms = findInMasterView('*', "PRO2 = '{0}'".format(val.lot_no))
  64. #pressInfo = findPressInfo(codeno.replace("-", ""),val.lot_no, filters)
  65. #print("master view")
  66. #print(ms)
  67. if ms:
  68. ws.cell(column = ccode, row=35, value = ms[0].MI24)
  69. #ws[c+'38'] = ms[0].STD_Balance
  70. ws.cell(column = ccode , row=37, value = ms[0].PRO6)
  71. #ws[c+'44'] = ms[0].PRO5
  72. ws.cell(column = ccode, row = 43, value = ms[0].PRO10)
  73. ws.cell(column = ccode, row = 42, value = ms[0].PRO12)
  74. #if pressInfo:
  75. ws.cell(column = ccode , row=39, value = val.Press_UserName)
  76. ws.cell(column = ccode, row = 40, value = val.Press_McName)
  77. #print(type(pressInfo[0].Insp_Date))
  78. #ws[c+'46'].number_format = "Short Date"
  79. ws.cell(column = ccode, row = 46 , value = val.Insp_Date.date())
  80. #print(type(ws[c+'46'].value))
  81. #ws[c+'46'].style = dateStyle
  82. #ws[c+'46'].value = datetime.datetime(2010, 7, 21)
  83. #print(ws[c+'46'].number_format)
  84. #ws[c+'46']. = datetime.datetime
  85. ws.cell(column = ccode , row = 44, value = val.FG_Qty)
  86. dws = updateLength(val.lot_no)
  87. for j,v in enumerate(dws):
  88. ws.cell(column = ccode , row = 48+v.row_no , value = v.weight)
  89. dws = updateUb(val.lot_no)
  90. for j,v in enumerate(dws):
  91. ws.cell(column = ccode , row = 171+v.row_no , value = v.weight)
  92. ccode += 1
  93. c1 = LineChart()
  94. c1.legend.position = "t";
  95. c1.title = "Graph of Result Cp Unbalance"
  96. c1.title.font = Font(underline=Font.UNDERLINE_SINGLE)
  97. c1.y_axis.title = "Unb Weight"
  98. c1.y_axis.number_format = "#,##0.00"
  99. c1.x_axis.title = "Lot No"
  100. c1.width = 30
  101. c1.height = 10
  102. #print(len(values))
  103. lt = Reference(ws, min_col=2, max_col=len(values)+1, min_row=45, max_row=45)
  104. data = Reference(ws, min_col=1, max_col=len(values)+1, min_row=34, max_row=34)
  105. maxUB = Reference(ws, min_col=1, max_col=len(values)+1, min_row=29, max_row=29)
  106. minUB = Reference(ws, min_col=1, max_col=len(values)+1, min_row=30, max_row=30)
  107. avgUB = Reference(ws, min_col=1, max_col=len(values)+1, min_row=31, max_row=31)
  108. vsStd = Reference(ws, min_col=1, max_col=len(values)+1, min_row=36, max_row=36)
  109. c1.add_data(data, from_rows=True, titles_from_data=True)
  110. c1.add_data(minUB, from_rows=True, titles_from_data=True)
  111. c1.add_data(avgUB, from_rows=True, titles_from_data=True)
  112. c1.add_data(vsStd, from_rows=True, titles_from_data=True)
  113. c1.add_data(maxUB, from_rows=True, titles_from_data=True)
  114. s1 = c1.series[0]
  115. s1.marker.symbol = "triangle"
  116. s1.graphicalProperties.line.noFill = True
  117. s1 = c1.series[1]
  118. s1.marker.symbol = "circle"
  119. s1.graphicalProperties.line.noFill = True
  120. s1 = c1.series[2]
  121. s1.marker.symbol = "square"
  122. s1.graphicalProperties.line.noFill = True
  123. s1 = c1.series[4]
  124. s1.marker.symbol = "diamond"
  125. s1.graphicalProperties.line.noFill = True
  126. c1.set_categories(lt)
  127. c1.x_axis.txPr = RichText(bodyPr=RichTextProperties(anchor="ctr",anchorCtr="1",rot="-2700000",
  128. spcFirstLastPara="1",vertOverflow="ellipsis",wrap="square"),
  129. p=[Paragraph(pPr=ParagraphProperties(defRPr=CharacterProperties()), endParaRPr=CharacterProperties())])
  130. ws.add_chart(c1, "A7")
  131. #newws.title = name
  132. #copy data cp ws
  133. #insert values in the sheet
  134. def findInMasterView(select, where):
  135. global cursor
  136. global env
  137. tempResult = []
  138. views = []
  139. if env == "prod":
  140. views = ["bel_master_view", "e_master_view", "mg_master_view", "v_master_view"]
  141. else:
  142. views = ["bel_master_view_dev", "e_master_view_dev", "mg_master_view_dev", "v_master_view_dev"]
  143. ts = []
  144. for v in views:
  145. sqlQuery = "select {0} from {1} where {2}".format(select, v, where)
  146. ts.append(sqlQuery);
  147. qj = ';'.join(ts)
  148. #print(qj)
  149. merged = []
  150. for t in ts:
  151. merged += cursor.execute(t)
  152. if len(merged) > 0:
  153. return merged
  154. return merged
  155. def findPressInfo(code, lot, year):
  156. global cursor
  157. global env
  158. fyear = year.replace("created_at", "Insp_Date")
  159. q = "select * from tb_fg_pressinfo_lotlist where ProductCode = '{0}' and LotNo = '{1}' and {2}" \
  160. .format(code, lot, fyear)
  161. cursor.execute(q)
  162. return cursor.fetchall()
  163. def updateLength(lotno):
  164. global cursor
  165. global wb
  166. q = "select * from data_wb where lot_no = '{0}' and judgement='OK' order by row_no asc".format(lotno)
  167. #print(q);
  168. return cursor.execute(q)
  169. def updateUb(lotno):
  170. global cursor
  171. global wb
  172. q = "select * from data_wb where lot_no = '{0}' and judgement='NG' order by row_no asc".format(lotno)
  173. #print(q);
  174. return cursor.execute(q)
  175. def createExcel(codeno, filters):
  176. global cursor
  177. global wb
  178. global dateStyle
  179. ws = wb["Data Cp"]
  180. codeString = ""
  181. if codeno.find('-') != -1:
  182. codeString = codeno
  183. else:
  184. codeString = codeno[0] + "-" + codeno[1:5] + "-" + codeno[5:9] + "-" + codeno[9:10]
  185. if filters is not None:
  186. q = """select * from lot_summary_wb as lt
  187. inner join tb_fg_pressinfo_lotlist as press
  188. on lt.lot_no = press.LotNo
  189. and replace(lt.code, '-', '') = press.ProductCode
  190. where code = '{0}' and {1}
  191. order by press.Insp_Date asc
  192. """.format(codeString, filters)
  193. else:
  194. q = """select * from lot_summary_wb as lt
  195. inner join tb_fg_pressinfo_lotlist as press
  196. on lt.lot_no = press.LotNo
  197. and replace(lt.code, '-', '') = press.ProductCodes
  198. where code = '{0}'
  199. order by press.Insp_Date asc
  200. """.format(codeString)
  201. #print(q)
  202. cursor.execute(q)
  203. rows = cursor.fetchall()
  204. #print(rows)
  205. y = {}
  206. for r in rows:
  207. t = "{0}-{1}".format(r.created_at.year, r.created_at.month)
  208. if t in y:
  209. y[t].append(r)
  210. else:
  211. y[t] = []
  212. y[t].append(r)
  213. #print(y)
  214. for k, v in y.items():
  215. createWS(k,v, codeno, filters)
  216. #print(ws._charts)
  217. cust = findCustomer(codeno.replace("-", ""))
  218. ws["B2"] = cust[0].customer
  219. ws["B3"] = codeno.replace("-", "")
  220. ws["B4"] = cust[0].sizestring
  221. ws["B5"] = cust[0].spec
  222. bcode = ord('B')
  223. ccode = 2
  224. for idx, val in enumerate(rows):
  225. #print(idx)
  226. c = chr(bcode + idx)
  227. #print(val.lot_no)
  228. if ( bcode + idx) > ord('Z'):
  229. r = bcode + idx - ord('Z')
  230. c = 'A' + chr(ord('A') + (r - 1))
  231. #print("c = "+c)
  232. ws.cell(column= ccode, row=45, value = val.lot_no)
  233. ms = findInMasterView('*', "PRO2 = '{0}'".format(val.lot_no))
  234. #pressInfo = findPressInfo(codeno.replace("-", ""),val.lot_no, filters)
  235. #print("master view")
  236. #print("ms")
  237. #print(ms)
  238. if ms:
  239. ws.cell(column = ccode, row=35, value = ms[0].MI24)
  240. #ws[c+'38'] = ms[0].STD_Balance
  241. ws.cell(column = ccode , row=37, value = ms[0].PRO6)
  242. #ws[c+'44'] = ms[0].PRO5
  243. ws.cell(column = ccode, row = 43, value = ms[0].PRO10)
  244. ws.cell(column = ccode, row = 42, value = ms[0].PRO12)
  245. #if pressInfo:
  246. ws.cell(column = ccode , row=39, value = val.Press_UserName)
  247. ws.cell(column = ccode, row = 40, value = val.Press_McName)
  248. #print(type(pressInfo[0].Insp_Date))
  249. #ws[c+'46'].number_format = "Short Date"
  250. ws.cell(column = ccode, row = 46 , value = val.Insp_Date.date())
  251. #print(type(ws[c+'46'].value))
  252. #ws[c+'46'].style = dateStyle
  253. #ws[c+'46'].value = datetime.datetime(2010, 7, 21)
  254. #print(ws[c+'46'].number_format)
  255. #ws[c+'46']. = datetime.datetime
  256. ws.cell(column = ccode , row = 44, value = val.FG_Qty)
  257. dws = updateLength(val.lot_no)
  258. for j,v in enumerate(dws):
  259. ws.cell(column = ccode , row = 48+v.row_no , value = v.weight)
  260. dws = updateUb(val.lot_no)
  261. for j,v in enumerate(dws):
  262. ws.cell(column = ccode , row = 171+v.row_no , value = v.weight)
  263. ccode += 1
  264. ut = int(time.time())
  265. filename = "cp{0}.xlsx".format(codeno.replace("-", ""))
  266. outfile = './public/excel/'+filename
  267. wb.save(filename = outfile)
  268. print(filename)
  269. if __name__ == "__main__":
  270. env = sys.argv[1]
  271. code = sys.argv[2]
  272. #print(len(sys.argv))
  273. df = None
  274. if len(sys.argv) == 4:
  275. filter = sys.argv[3]
  276. #import ast
  277. #df = ast.literal_eval(filter)
  278. #print(df['date'])
  279. df = filter
  280. global cnxn
  281. global cursor
  282. if env == "prod":
  283. cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=192.168.0.253;DATABASE=OB2011DB;UID=user1;PWD=1234')
  284. cursor = cnxn.cursor()
  285. else:
  286. cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=db;DATABASE=OB2011DB;UID=admin;PWD=1234')
  287. cursor = cnxn.cursor()
  288. #print("code is "+code)
  289. createExcel(code, df)