将Postgresql表导出为带有标题的Excel

时间:2016-06-23 16:09:39

标签: python postgresql

我写了一个python脚本将表从postgresql导出到Excel,它的工作完美,但我得到的文件没有标题(只有数据) 这是我的代码:

#!/usr/bin/python
import os
import psycopg2
"""Fichier en sortie"""
output_file_1=r"path\myfile.xls"

try:
    conn = psycopg2.connect(database="", user="", password="", host="", port="")
except:
    print "Connexion failed"

cur = conn.cursor()

try:
    cur.execute('''select * from table1''')

#cur2.execute("""select * from cores""");
except:
    print"Enable to execute query"
rows=cur.fetchall()
try:
    import xlwt
except ImportError: "import of xlwt module failed"

# Make spreadsheet
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(os.path.split(output_file_1)[1])

worksheet.set_panes_frozen(True)
worksheet.set_horz_split_pos(0)
worksheet.set_remove_splits(True)

# Write rows
for rowidx, row in enumerate(rows):
    for colindex, col in enumerate(row):
    worksheet.write(rowidx, colindex, col)

# All done
workbook.save(output_file_1)
#print"finished"


print "finished!!"
conn.commit()
conn.close()

我想获得带标题

的excel文件

1 个答案:

答案 0 :(得分:1)

您可以使用cur.description获取列名称。它返回一个元组元组,列名作为每个包含元组的第一个元素。

for colidx,heading in enumerate(cur.description):
    worksheet.write(0,colidx,heading[0]) # first element of each tuple

# Write rows
for rowidx, row in enumerate(rows):
    for colindex, col in enumerate(row):
    worksheet.write(rowidx+1, colindex, col) # increment `rowidx` by 1

编辑:要跳过前两行并开始在第三行写作,请执行以下操作:

rows_skipped = 2
for colidx,heading in enumerate(cur.description):
    worksheet.write(rows_skipped,colidx,heading[0])

# Write rows
for rowidx, row in enumerate(rows):
    for colindex, col in enumerate(row):
    worksheet.write(rowidx+rows_skipped, colindex, col)