#!/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文件答案 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)