python - 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 脚本中使用的所有代码(基本上是创建审计跟踪)。
您可以提供的任何帮助将不胜感激!
解决方案
我做了一个例子,如何将脚本的代码添加到第二张表中,应该可以# 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()
推荐阅读
- c# - MSB401 “ResolveLibraryProjectImports”任务意外失败。System.IO.IOException
- vue.js - [Vue 警告]:v-on 处理程序中的错误:“TypeError:无法读取未定义的属性 'mutate'”
- r - DT::datatable 的 for 循环输出,带有 Rmarkdown
- java - 当鼠标在矩形中时,包含方法不返回 true
- r - r 对象列表 POINT(坐标)
- django - 在postgres上使用'unaccent'时的Django django.core.exceptions.FieldError
- javascript - 单击按钮时添加或删除元素
- wordpress - 如何将详细信息作为 wordpress 中的电子邮件发送给注册到管理员的用户?
- javascript - 如何与 appendChild 一起添加字符串?
- html - 为什么我的 index.html 文件失去了颜色语法?