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")
原文地址:https://www.cnblogs.com/hbxZJ/p/13331535.html