python connected to the database, query results to write data to excel

Python data link using a database query, the query result is written into Excel, to achieve two major steps on the way first, check data, the second, write Excel.

First, the need to import the package

import time
import xlwt
from commontool import dbtool
import os

 

Second, check the data and returns the query results

  Query data into a specified date, using the specified date of the transaction date range queries in the database. Because the incoming date to a string, the first step you need to convert the incoming string into an array of time, then the second step converts the incoming date to a time format you want.

class the WriteFile: 
    File = r " F: \ Python \ PycharmProjects \ pythonpractice \ fileshandle \ Files " 
DEF queryData (Self, DATE): "" " query the database results " "" self.date = DATE datestruct = time.strptime (Self. DATE, " % m%% the Y D " ) # to convert the string to a time array DATE = the time.strftime ( " % Y-M-% D% " , datestruct) # converted into other formats time startTime = DATE + ' 00:00:00 ' endtime = date + ' 23:59:59' db = dbtool.db() orderquery = "select merchantid,payorderid,state,paytime,innerbank from ordersummary where paytime between '%s' and '%s' ; " %(starttime,endtime) res = db.dbquery(db.dbconnect()[3],orderquery).fetchall() return res

Third, write the query results to Excel

  Written query results to Excel, used here is xlwt module, first thing to do is: Create an Excel, and then create a sheet pages, you need the header, then also need to write a header. The format of the header is a list.

  It should be noted that:

  (1) range does not include the stop function is the number, so here you want to write all data queries, then you need to len (res) +1. For example: Query Results 5, when the range (1,4), only 1,2,3,4, will miss 5, so it is necessary to add a 1 query results.

  The second line (2) row = 1 representative of Excel (the first row is the header), the data to be written in the second line of inquiry, it should query data written in the first row, so sheet.write (row , COL, RES [-Row. 1 ] [COL]) using a row-1.

    DEF write_excel (Self, RES):
         "" " Operation Excel " "" 
        Book = xlwt.Workbook ()                                      # create a new Excel 
        Sheet = book.add_sheet ( ' export data ' )                           # Create a Sheet 
        title = [ ' business number ' , ' serial number ' , ' trading status ' , ' trading hours ' , ' trade channels ']     # Write header 

        # cycle header page is written to the sheet 
        I = 0
        for header in title:
            sheet.write(0,i,header)
            i+=1

        # 写数据
        for row in range(1,len(res)+1):
            for col in range(0,len(res[row-1])):
                sheet.write(row,col,res[row-1][col])
                col+=1
            row+=1
        book.save(self.file+"\交易导出.xls")
        print("导出成功")

Four, it is determined whether to repeat the generating Excel

  Is generated in a file path, determines whether to repeat generation requires the presence of the path of the file, if present, deleted, or renamed, then move to the next or the backup path, is used herein to delete repeated.

  Delete files here to use the os module.

    DEF judge_file_exist (Self):
         IF os.path.exists (self.file + " \ Trading Export .xls " ): 
            os.remove (self.file + " \ Trading Export .xls " )

Fifth, the main flow is more than a few steps, the main function will now need to string them together.

  First determine whether the file exists, then call write file method.

    def writefile(self):
        date = '20191028'
        self.judge_file_exist()
        self.write_excel(self.querydata(date))

 

Guess you like

Origin www.cnblogs.com/deliaries/p/11792137.html