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")
  • 相关阅读:
    Angle Beats Gym
    MUV LUV UNLIMITED Gym
    Balanced Diet Gym
    数位dp HDU
    数位dp CodeForces
    数位dp HDU
    有依赖的背包 洛谷P1064 金明的预算方案 (不是分组背包)
    多重背包+二进制拆分 POJ1014
    单调队列优化dp 入门 洛谷P2627 修剪草坪
    01背包 + 排序 (记忆化搜索) 骄傲的商人(HDU
  • 原文地址:https://www.cnblogs.com/hbxZJ/p/13331535.html
Copyright © 2011-2022 走看看