如何将 python 脚本的 aws athena 输出存储在 excel 中?

How to store aws athena output from python script in excel?

我正在使用 python 脚本和 pyathena 库从 aws athena 进行查询,我得到了 table.

形式的正确输出

Output

现在的问题是我想将输出存储在 excel。

任何人都可以建议我使用 python 脚本如何将输出存储在 Excel 中吗?

这是我在 aws athena 中用于查询的代码:

from pyathena import connect
import os
import pandas as pd
%matplotlib inline

conn = connect(aws_access_key_id='*****',
                 aws_secret_access_key='*****',
                 s3_staging_dir='s3://****/',
                 region_name='us-west-1')

cursor = conn.cursor()
%time cursor.execute("SELECT * from my_table;")

提前致谢...

输出到Excel不限于创建xlsx文件,你也可以写成csv,让Excel加载csv文件。

您可以使用类似以下内容创建多个工作表:

from pandas import ExcelWriter
def save_xls(list_dfs, dfs_names, xls_path):
    with ExcelWriter(xls_path) as writer:
        for df,name in zip(list_dfs, dfs_names):
            df.to_excel(writer,name)
        writer.save()

然后您可以调用函数对数据进行一些转换,例如数据透视表甚至颜色:

save_xls(
    (raw.style.format("{:,.0f}"), 
     actual_table.style.format("{:,.0f}"), 
     diff_table.style.applymap(_color_red_or_green).format("{:,.0f}"), 
     ratio_table.style.applymap(_color_red_yellow_or_green).format("{:.3f}")),
    ('Raw',
    'Actuals',
    'Diff',
    'Ratio'),
    results_with_format.xlsx')

例如,根据单元格的值使用三种颜色进行格式化:

def _color_red_yellow_or_green(val):
    color = 'red' if val > 0.1 else 'yellow' if val > 0.05 else 'green'
    return 'background-color: %s' % color

您可以使用pandas查询和保存excel中的数据:

data = pd.read_sql("SELECT * from my_table;",conn) 
data.to_excel('data.xlsx') 

根据您需要将数据插入 sheet 的精确程度,您可以查看 OpenPyXl - https://openpyxl.readthedocs.io

当我需要将 Athena 结果插入工作簿中的特定单元格 and/or 工作 sheet 时,我会使用它。当我需要比显示 table 个结果更精确的时候。您可以引用单个单元格,例如 worksheet['A53'] = 12345