Advertisement
Guest User

Untitled

a guest
Apr 17th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.36 KB | None | 0 0
  1. Traceback (most recent call last):
  2. File "C:Python34timerange.py", line 75, in <module>
  3. worksheet.write(r,0,row[0])
  4. File "C:Python34libsite-packagesxlsxwriterworksheet.py", line 64, in cell_wrapper
  5. return method(self, *args, **kwargs)
  6. File "C:Python34libsite-packagesxlsxwriterworksheet.py", line 436, in write
  7. return self.write_string(row, col, *args)
  8. File "C:Python34libsite-packagesxlsxwriterworksheet.py", line 64, in cell_wrapper
  9. return method(self, *args, **kwargs)
  10. File "C:Python34libsite-packagesxlsxwriterworksheet.py", line 470, in write_string
  11. string_index = self.str_table._get_shared_string_index(string)
  12. File "C:Python34libsite-packagesxlsxwritersharedstrings.py", line 128, in _get_shared_string_index
  13. if string not in self.string_table:
  14. TypeError: unhashable type: 'bytearray'
  15.  
  16. [mysql]
  17. host = localhost
  18. database = db_name
  19. user = root
  20. password = blahblah
  21.  
  22. from configparser import ConfigParser
  23.  
  24. def read_db_config(filename=’config.ini’, section=’mysql’):
  25. “”” Read database configuration file and return a dictionary object
  26. :param filename: name of the configuration file
  27. :param section: section of database configuration
  28. :return: a dictionary of database parameters
  29. “””
  30. # create parser and read ini configuration file
  31. parser = ConfigParser()
  32. parser.read(filename)
  33.  
  34. # get section, default to mysql
  35. db = {}
  36. if parser.has_section(section):
  37. items = parser.items(section)
  38. for item in items:
  39. db[item[0]] = item[1]
  40. else:
  41. raise Exception(‘{0} not found in the {1} file’.format(section, filename))
  42.  
  43. return db
  44.  
  45. # Establish a MySQL connection
  46. from mysql.connector import MySQLConnection, Error
  47. from python_mysql_dbconfig import read_db_config
  48. db_config = read_db_config()
  49. conn = MySQLConnection(**db_config)
  50. cursor = conn.cursor(raw=True)
  51.  
  52. #to export to excel
  53. import xlsxwriter
  54. from xlsxwriter.workbook import Workbook
  55.  
  56. #to get the csv converter functions
  57. import os
  58. import subprocess
  59. import glob
  60.  
  61. #to get the datetime functions
  62. import datetime
  63. from datetime import datetime
  64. import dateutil.parser
  65.  
  66. #creates the path needed for output files
  67. path = 'C:/Python34/output_files/'
  68.  
  69. #creates the workbook
  70. output_filename = input('output filename:')
  71. workbook = xlsxwriter.Workbook(path + output_filename + '.xlsx')
  72. worksheet = workbook.add_worksheet()
  73.  
  74. #formatting definitions
  75. bold = workbook.add_format({'bold': True})
  76. date_format = workbook.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'})
  77. timeShape = '%Y-%m-%d %H:%M:%S'
  78.  
  79. #actual query
  80.  
  81.  
  82. query = (
  83. "SELECT sent_time, delivered_time, OBJ, id1_active, id2_active, id3_active, id1_inactive, id2_inactive, id3_inactive, location_active, location_inactive FROM table1 "
  84. "WHERE sent_time BETWEEN %s AND %s"
  85. )
  86. userIn = dateutil.parser.parse(input('start date:'))
  87. userEnd = dateutil.parser.parse(input('end date:'))
  88.  
  89.  
  90. # Execute sql Query
  91. cursor.execute(query,(userIn, userEnd))
  92. result = cursor.fetchall()
  93.  
  94.  
  95. #sets up the header row
  96. worksheet.write('A1','sent_time',bold)
  97. worksheet.write('B1', 'delivered_time',bold)
  98. worksheet.write('C1', 'customer_name',bold)
  99. worksheet.write('D1', 'id1_active',bold)
  100. worksheet.write('E1', 'id2_active',bold)
  101. worksheet.write('F1', 'id3_active',bold)
  102. worksheet.write('G1', 'id1_inactive',bold)
  103. worksheet.write('H1', 'id2_inactive',bold)
  104. worksheet.write('I1', 'id3_inactive',bold)
  105. worksheet.write('J1', 'location_active',bold)
  106. worksheet.write('K1', 'location_inactive',bold)
  107. worksheet.autofilter('A1:K1') #dropdown menu created for filtering
  108.  
  109.  
  110. #print into client to see that you have results
  111. print(" sent_time ", " delivered_time ", "OBJ", "t id1_active ", " id2_active ", " id3_active ", "t", " id1_inactive ", " id2_inactive ", " id3_inactive ", "tlocation_active", "tlocation_inactive")
  112. for row in result:
  113. print(*row, sep='t')
  114.  
  115.  
  116. # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
  117. for r, row in enumerate(result, start=1): #where you want to start printing results inside workbook
  118. for c, col in enumerate(row):
  119. worksheet.write_datetime(r,0,row[0], date_format)
  120. worksheet.write_datetime(r,1, row[1], date_format)
  121. worksheet.write(r,2, row[2])
  122. worksheet.write(r,3, row[3])
  123. worksheet.write(r,4, row[4])
  124. worksheet.write(r,5, row[5])
  125. worksheet.write(r,6, row[6])
  126. worksheet.write(r,7, row[7])
  127. worksheet.write(r,8, row[8])
  128. worksheet.write(r,9, row[9])
  129. worksheet.write(r,10, row[10])
  130.  
  131.  
  132.  
  133.  
  134. #close out everything and save
  135. cursor.close()
  136. workbook.close()
  137. conn.close()
  138.  
  139. #print number of rows and bye-bye message
  140. print ("- - - - - - - - - - - - -")
  141. rows = len(result)
  142. print ("I just imported "+ str(rows) + " rows from MySQL!")
  143. print ("")
  144. print ("Good to Go!!!")
  145. print ("")
  146.  
  147.  
  148. #CONVERTS JUST CREATED FILE TO CSV
  149.  
  150. # set path to folder containing xlsx files
  151.  
  152. out_path ='C:/Python34/csv_files'
  153. os.chdir(path)
  154.  
  155.  
  156. # find the file with extension .xlsx
  157. xlsx = glob.glob(output_filename + '.xlsx')
  158.  
  159. # create output filenames with extension .csv
  160. csvs = [x.replace('.xlsx','.csv') for x in xlsx]
  161.  
  162. # zip into a list of tuples
  163. in_out = zip(xlsx,csvs)
  164.  
  165. # loop through each file, calling the in2csv utility from subprocess
  166. for xl,csv in in_out:
  167. out = open(csv,'w')
  168. command = 'c:/python34/scripts/in2csv %s\%s' % (path,xl)
  169. proc = subprocess.Popen(command,stdout=out)
  170. proc.wait()
  171. out.close()
  172.  
  173. print('XLSX and CSV files named ' + output_filename + ' were created')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement