zoukankan      html  css  js  c++  java
  • python导出execl

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import psycopg2
    import openpyxl
    from datetime import datetime
    
    
    def getData():
        conn = psycopg2.connect(database='contracts', user='exxxxxx', password='123456', host='127.0.0.1', port='5432')
        cur = conn.cursor()
        tableName = 'contracts'
        commandFindColumn = "select COLUMN_NAME from information_schema.COLUMNS where table_name='%s' " % (tableName)
        cur.execute(commandFindColumn)
        columnRows = cur.fetchall()
        '''导出outcome的全部'''
        commandFindRecord = "select * from %s " % (tableName)
        cur.execute(commandFindRecord)
        recordRows = cur.fetchall()
        conn.commit()
        cur.close()
        conn.close()
        return columnRows, recordRows
    
    
    def writeDataToExcel(name):
        columnRows, recordRows = getData()
        print(columnRows)
        print(len(columnRows))
        print(recordRows)
        print(len(recordRows))
    
        wb = openpyxl.Workbook()
        wb.create_sheet(name, 0)
        sheet = wb[name]
    
        today = datetime.today()  # 获取当前日期,得到一个datetime对象如:(2019, 7, 2, 23, 12, 23, 424000)
        today_date = datetime.date(today)  # 将获取到的datetime对象仅取日期如:2019-7-2
    
        # 当列数超过26时,添加AA,AB,AC...
        myAlphbet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                     'U', 'V', 'W', 'X', 'Y', 'Z','AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK']
        for i in range(len(columnRows)):
            loc = myAlphbet[i] + str(1)
            sheet[loc] = columnRows[i][0]
    
        for i in range(len(recordRows)):
            for j in range(len(recordRows[i])):
                loc = myAlphbet[j] + str(i + 2)
                sheet[loc] = recordRows[i][j]
    
        wb.save(name + '_' + str(today_date) + '.xlsx')  # 以传递的name+当前日期作为excel名称保存
    
    
    if __name__ == '__main__':
        writeDataToExcel("outcome")
        print("succeed")
  • 相关阅读:
    gThumb 3.1.2 发布,支持 WebP 图像
    航空例行天气预报解析 metaf2xml
    Baruwa 1.1.2 发布,邮件监控系统
    Bisect 1.3 发布,Caml 代码覆盖测试
    MoonScript 0.2.2 发布,基于 Lua 的脚本语言
    Varnish 入门
    快速增量备份程序 DeltaCopy
    恢复模糊的图像 SmartDeblur
    Cairo 1.12.8 发布,向量图形会图库
    iText 5.3.4 发布,Java 的 PDF 开发包
  • 原文地址:https://www.cnblogs.com/hbxZJ/p/13331535.html
Copyright © 2011-2022 走看看