在 Python 中使用 header 将 Postgresql Table 导出到 excel

Export Postgresql Table to excel with header in Python

我的代码有效,但它没有带名称的 header,它只带数字 0 1 ... 10,我该怎么办?

Utils_db.py

    def consulta_sql(sql):
    try:
       connection = psycopg2.connect(user="postgres",
                                    password="postgres",
                                    host="localhost",
                                    port="5432",
                                    database="tb_cliente")
       cursor = connection.cursor()
    except (Exception, psycopg2.Error) as error:
           
    try:
       cursor.execute(sql)
       connection.commit()
       
    except (Exception, psycopg2.Error) as error:
       
    finally:
       if connection:
          result = cursor.fetchall()
          cursor.close()
          connection.close()
          return result

main.py

Excel = Utils_db.consulta_sql("Select * from corantes")

df = pd.DataFrame(Excel)
df.to_excel('C:/Users/Dnaxis2/Downloads/Corantes.xlsx', index=False)

生成excel

0   1   2   3   4   5   6   7   8   9   10

1   FF  BK  20  200 10  200 200 200 200 30

2   PP  BK  100 500 150 0   0   0   35  30

正确excel(必须这样来)

Corant Pags Table Polo Jetta Fox Ps Ilu Kik Qly

1   FF  BK  20  200 10  200 200 200 200 30

2   PP  BK  100 500 150 0   0   0   35  30

您可以要求 psycopg2 return 将结果作为字典,使用列名作为字典的键。

将值 RealDictCursor(从 psycopg2.extras 导入)传递给连接方法中的 cursor_factory 参数。

该行将是

from psycopg2.extras import RealDictCursor
connection = psycopg2.connect(user="postgres",
                                password="postgres",
                                host="localhost",
                                port="5432",
                                database="tb_cliente",
                                cursor_factory=RealDictCursor)