#_*_coding:utf-8_*_ImportMySQLdbImportXLWT fromDatetimeImportdatetimedefget_data (SQL):#Create a database connection.conn = MySQLdb.connect (host='127.0.0.1', user='Root', passwd='123456', db='Test', port=3306,charset='UTF8') #Creating CursorsCur =conn.cursor ()#execute the query,cur.execute (SQL)#because the query statement returns only the number of affected record bars and does not return the actual values in the database, Fetchall () is required here to get all the content. result =Cur.fetchall ()#Close Cursorscur.close ()#To close a database connectionConn.close#returns the result to the function caller. returnresultdefWrite_data_to_excel (name,sql):#Pass SQL as a parameter call Get_data and assign the result to results (result is a nested tuple)result =get_data (SQL)#instantiate a Workbook () object (that is, an Excel file)WBK =XLWT. Workbook ()#Create a new Excel sheet named Sheet1. The CELL_OVERWRITE_OK =true here is to be able to repeat operations on the same cell. Sheet = Wbk.add_sheet ('Sheet1', cell_overwrite_ok=True)#gets the current date, and gets a DateTime object such as: (8, 9, up, up, 424000)Today =Datetime.today ()#The DateTime object that will be fetched takes only the date such as: 2016-8-9Today_date =datetime.date (today)#iterate through the elements in result. forIinchxrange (len (Result)):#iterates over each child element of result, forJinchxrange (len (result[i)):#writes each element of each row to Excel by line number I, column number J. Sheet.write (I,j,result[i][j])#saves the current date as an Excel name in the passed name+. Wbk.save (Name+str (today_date) +'. xls')#If the file is not import, execute the following code. if __name__=='__main__': #define a dictionary, key for the corresponding data type is also used as Excel name, value is the query statementDb_dict = {'Test':'SELECT * FROM Student'} #iterate through the keys and value of each element of the dictionary. forKvinchDb_dict.items ():#Call the Write_data_to_excel function with each key and value in the dictionary. Write_data_to_excel (K,V)
Python Export data Generation Excel report