【问题标题】:How to export exact format table from teradata to excel?如何将精确格式的表格从 teradata 导出到 excel?
【发布时间】:2019-12-20 04:55:22
【问题描述】:

对于工作中的项目,我需要从 teradata 导出到 excel 一个 sql 请求。

到目前为止,我已成功将多个请求完全导出到我的 excel 文件中,但输出格式并不完全符合我的要求。实际上,输出不尊重原始表,只是逐行给出了连接,例如: 一种 1('000000000DUM','RRFOR','','','NOTE_CONTREP','20.00') 我想要

A1 :000000000DUM B1 : RRFOR C1 :'' D1 : '' E1 : NOTE_CONTREP F1 : 20.00

这是我的代码:

def KPI_MAKER(instid):
conn=pyodbc.connect('DRIVER={Teradata};DBCNAME=FTGPRDTD;UID='+str('L291506')+';PWD='+str('Pilote06!')+';QUIETMODE=YES;')
Agg=str("sel code_gen1,code_gen2,cd_prd_cpta,lieu_stkph_cd,don_source_cd,incorrect_value from DB_FTG_SRS_DATALAB.mdc_ctrl_anomalie where rg_no = 'RGC-TIE-012'")
cursor = conn.cursor()
cursor.execute(Agg)
Agg_output = cursor.fetchall()
conn.close

df = pd.DataFrame(Agg_output)
writer = pd.ExcelWriter('KPI_FORTIS_13082019.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False, sheet_name='POC_output')    # sheet 0
writer.save()
print('done')

【问题讨论】:

    标签: python excel pandas teradata xlsxwriter


    【解决方案1】:

    问题在于fetchall 方法返回row 对象列表而不是元组列表。添加从行到元组的 Agg_output 转换将允许 DataFrame 方法执行您想要的操作。但是,为什么要打扰光标呢?只需让 pandas 直接从查询中创建数据框:

    df = pd.read_sql(Agg,conn)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2017-02-22
      相关资源
      最近更新 更多