2016-06-23 54 views
3

練成我whrote一個python腳本從PostgreSQL的導出表到Excel,它是在這裏完美的作品,但我得到無標題(僅數據)的文件 是我的代碼:出口PostgreSQL表與頭

#!/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

你可以使用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) 
+0

謝謝它的作品,現在我wondring我怎麼能跳過2個第一行並從第三輪開始吶喊? – Hchliyah

+0

請參閱編輯答案。 – bernie

+0

它不工作! – Hchliyah