首页 > 解决方案 > 无法使用 python 从 postgres 表中提取数据到 .ods 文件

问题描述

我正在尝试使用以下代码在 ods 文件中收集 postgres 查询的输出。我创建了一个read_table成功读取 postgres 表的函数。

def read_table()
     import psycopg2 as ps
     import sys

      con =None
      try:
      con=ps.connect("host, dbname, user,pwd....")
      cur=con.cursor()
      cur.execute("Select * from table_name")
      rows=cur.fetchall()
      for(row in rows):
            print(row)
      cur.close()
      except (Exception, ps.DatabaseError) as error:
      print(error)
      finally:
          if con is not None:
             con.close()

  from collections import OrderedDict
  from pyexcel_ods import save_data
  data=OrderedDict()
  raw_data=read_table()
  raw_data.update({'DATA':raw_data})
  save_data("/home/myfile.ods", raw_data)

该表打印在 python shell 上,但未写入 .ods 文件。它给出以下错误:

raw_data.update({'DATA':raw_data})
AttributeError: 'NoneType' object has no attribute

如何在 ods 文件中保存和提取表格?所有软件包和模块都已安装,但我仍然收到此错误。

我是python的新手,所以请指导我。我在 Ubuntu 上使用 Postgres 数据库,使用 Idle3。

标签: pythonpostgresqlubuntuods

解决方案


您的方法 raw_data 不返回任何内容。您不想打印行,而是希望返回它们或产生它们,如下所示:return rowyield row代替print(row)

但是,可以使用 pandas 库在几行代码中完成您需要的操作:https ://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html https://pandas.pydata .org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html


推荐阅读