Python implements an example of exporting data to generate excel reports

  • 2020-06-07 04:51:13
  • OfStack

This article illustrates Python's method of exporting data to generate excel reports. To share for your reference, specific as follows:


#_*_coding:utf-8_*_
import MySQLdb
import xlwt
from datetime import datetime
def get_data(sql):
  #  Creating a database connection .
  conn = MySQLdb.connect(host='127.0.0.1',user='root'\
              ,passwd='123456',db='test',port=3306,charset='utf8')
  #  Create a cursor 
  cur = conn.cursor()
  #  Execute the query, 
  cur.execute(sql)
  #  Since the query only returns the number of records affected and does not return the actual value in the database, this is required fetchall() To get everything. 
  result = cur.fetchall()
  # Close the cursor 
  cur.close()
  # Close the database connection 
  conn.close
  #  Returns the result to the function caller. 
  return result
def write_data_to_excel(name,sql):
  #  will sql Call passed as a parameter get_data And assign the result to result,(result for 1 Three nested tuples )
  result = get_data(sql)
  #  instantiation 1 a Workbook() object ( namely excel file )
  wbk = xlwt.Workbook()
  #  new 1 called Sheet1 the excel sheet . Here the cell_overwrite_ok =True In order to be identical 1 Repeat operation for each cell. 
  sheet = wbk.add_sheet('Sheet1',cell_overwrite_ok=True)
  #  Gets the current date, gets 1 a datetime Objects such as: (2016, 8, 9, 23, 12, 23, 424000)
  today = datetime.today()
  #  Will get datetime Object only takes a date such as: 2016-8-9
  today_date = datetime.date(today)
  #  traverse result Not a single element. 
  for i in xrange(len(result)):
    # right result Traverse each child element of, 
    for j in xrange(len(result[i])):
      # each 1 Each element of the row is numbered i, Column number j, Written to the excel In the. 
      sheet.write(i,j,result[i][j])
  #  In the passed name+ Current date as excel Save the name. 
  wbk.save(name+str(today_date)+'.xls')
#  If the file is not by import, Then execute the following code. 
if __name__ == '__main__':
  # define 1 A dictionary, key Is also used for the corresponding data type excel Name, value Is a query statement 
  db_dict = {'test':'select * from student'}
  #  Traversing each element of the dictionary key and value . 
  for k,v in db_dict.items():
    #  Use each of the dictionaries key and value call write_data_to_excel Function. 
    write_data_to_excel(k,v)

More about Python related content interested readers to view this site project: "Python file and directory skills summary", "Python skills summary text file", "Python data structure and algorithm tutorial", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article has been helpful in Python programming.


Related articles: