Python编写程序/脚本(不仅仅是输出)到ex

2024-04-25 13:49:14 发布

您现在位置:Python中文网/ 问答频道 /正文

出于文档/报告的目的,我想将为报表运行的脚本作为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脚本中使用的所有代码(基本上是创建审计跟踪)。你知道吗

如果您能提供任何帮助,我们将不胜感激!你知道吗


Tags: 代码import脚本dfforsqlscriptexcel
1条回答
网友
1楼 · 发布于 2024-04-25 13:49:14

我举了一个例子,如何将脚本的代码添加到第二页,应该能够用SQL部分替换# First sheet, use your SQL data下的部分。你知道吗

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

相关问题 更多 >