zoukankan      html  css  js  c++  java
  • python 连接数据库,查询结果写入数据到excel

    使用Python链接数据库查询数据,并将查询结果写入到Excel中,实现方法上主要有两步,第一,查数据,第二,写Excel。

    一、导入需要的包

    import time
    import xlwt
    from commontool import dbtool
    import os

    二、查数据,并返回查询结果

      查询数据传入指定日期,使用指定日期在数据库中查询该日期区间的交易。因为传入的日期为字符串,第一步需要将传入的字符串转换成时间数组,第二步再将传入的日期转换成自己想要的时间格式。

    class writefile:
        file = r"F:pythonPycharmProjectspythonpracticefileshandleFiles"
    def querydata(self,date): """查询数据库结果""" self.date = date datestruct = time.strptime(self.date,"%Y%m%d") # 将字符串转换成时间数组 date = time.strftime("%Y-%m-%d",datestruct) # 将时间转换成其他格式 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

    三、将查询结果写入到Excel

      将查询结果写入到Excel,这里使用的是xlwt模块,首先要做的是:创建一个Excel,再创建一个sheet页,需要表头的话,也需要写一个表头。表头的格式是一个列表。

      这里需要注意的是:

      (1)range函数是不包含stop数的,所以这里要写入查询的全部数据的话,需要给len(res)+1。比如:查询结果有5个,range(1,4)时,只能是1,2,3,4,就会漏掉5,所以需要给查询结果加上一个1。

      (2)row = 1代表Excel的第二行(第一行是表头),那么在第二行要写入查询的数据的话,应该写入查询数据的第一行,所以 sheet.write(row,col,res[row-1][col]) 中使用了row-1。

        def write_excel(self,res):
            """操作Excel"""
            book = xlwt.Workbook()                                     # 新建一个Excel
            sheet = book.add_sheet('导出数据')                          # 创建sheet
            title = ['商户号','流水号','交易状态','交易时间','交易渠道']    # 写表头
    
            # 循环将表头写入到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("导出成功")

    四、判断生成Excel是否重复

      文件生成是在一个路径下,要重复生成需要判断该路径下是否存在该文件,如果存在,则删除,或者重命名,再或者移动到备份路径下,这里使用的是重复就删除。

      删除文件这里使用到了os模块。

        def judge_file_exist(self):
            if os.path.exists(self.file+"交易导出.xls"):
                os.remove(self.file+"交易导出.xls")

    五、主要流程就是以上几步,现在需要主函数将其串起来。

      先判断文件是否存在,然后在调用写文件方法。

        def writefile(self):
            date = '20191028'
            self.judge_file_exist()
            self.write_excel(self.querydata(date))
  • 相关阅读:
    微信小程序之某个节点距离顶部和底部的距离 createSelectorQuery
    js正则手机号 验证
    算法将一个对象中的某一个key值变为true,其他值都为false
    更改上传框的大小
    Educational Codeforces Round 85 (Div. 2)
    Codeforces Round #632 (Div. 2)
    AtCoder Beginner Contest 161
    Codeforces Round #631 (Div. 2)
    Codeforces Round #630 (Div. 2)
    Codeforces Round #629 (Div. 3)
  • 原文地址:https://www.cnblogs.com/deliaries/p/11792137.html
Copyright © 2011-2022 走看看