Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Postgresql Table to excel with header

i whrote a python script to export table from postgresql to Excel and it's works perfectly,but i get a file without header (only data) here is my code:

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

I want to get an excel file with header

like image 386
Hchliyah Avatar asked Mar 28 '26 02:03

Hchliyah


1 Answers

You can use cur.description to get the column names. It returns a tuple of tuples with the column name as the first element of each contained tuple.

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

Edit: to skip the first two rows and begin writing on the third row do something like:

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)
like image 94
mechanical_meat Avatar answered Mar 29 '26 15:03

mechanical_meat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!