首页 > 解决方案 > Python编写程序/脚本(不仅仅是输出)到excel

问题描述

出于文档/报告的目的,我想纪念我为报告运行的脚本,作为输出到 excel 选项卡的一部分。这可能吗?

例如,如果我有以下代码:

import pyodbc
import pandas as pd

cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL 
Server};SERVER=relevantserver.com;UID=####;PWD=####; 
Trusted_Connection=yes')
cursor = cnxn.cursor()
script="""
  SELECT ID
    ,Type
    ,SubType
    ,Name
    ,RequestorLOB
    FROM db123
    ;
"""
cursor.execute(script)
columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()
df = pd.read_sql_query(script, cnxn)
writer = pd.ExcelWriter('C:/Users/myname/Desktop/testoutput.xlsx')
df.to_excel(writer, index=False, sheet_name='test1')
writer.save()

这将从 sql 脚本获取输出并创建一个数据框,然后创建一个 excel 文件并将该数据框放在工作表“test1”上。

我想创建第二个选项卡,其中包含在 python 脚本中使用的所有代码(基本上是创建审计跟踪)。

您可以提供的任何帮助将不胜感激!

标签: pythonpandas

解决方案


我做了一个例子,如何将脚本的代码添加到第二张表中,应该可以# First sheet, use your SQL data用你的 SQL 部分替换下面的部分。

import pandas as pd

# First sheet, use your SQL data
d = {'col1': [1, 2], 'col2': [3, 4]}
df_sheet_1 = pd.DataFrame(data=d)

# Second sheet, read the code of Python script, split it up on new lines, add to dataframe
with open(__file__) as input_file:
    python_script = input_file.read()

d = {'code':python_script.split('\n')}
python_df_sheet_2 = pd.DataFrame(data=d)


writer = pd.ExcelWriter('testoutput.xlsx')
df_sheet_1.to_excel(writer, index=False, sheet_name='test1')
python_df_sheet_2.to_excel(writer, index=False, sheet_name='python_code')
writer.save()

推荐阅读