繁体   English   中英

如何在 excel 中存储来自 python 脚本的 aws athena output?

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

我正在使用 python 脚本和 pyathena 库从 aws athena 进行查询,并且我以表格的形式获得了正确的 output。

Output

现在的问题是我想将 output 存储在 excel 中。

谁能建议我,使用 python 脚本我如何将 output 存储在 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;")

提前致谢...

The output to Excel is not limited to creating the xlsx file, which you can also write as csv and let Excel load the csv file.

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

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()

然后您可以调用 function 对您的数据进行一些转换,例如 pivot 表甚至 colors:

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')

例如,根据单元格的值使用三个 colors 进行格式化:

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') 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM