【发布时间】:2019-04-09 21:45:57
【问题描述】:
我的代码正在从文本文件中读取 SQL 查询并在 python 中一一执行。我正在尝试将查询结果保存在同一个 excel 中但在不同的选项卡/工作表中
import pyodbc as hive
import pandas as pd
filename =r'C:\Users\krkg039\Desktop\query.txt'
fd=open(filename,'r')
sqlFile=fd.read()
fd.close()
# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')
# Execute every command from the input file
for command in sqlCommands:
try:
con = hive.connect("DSN=SFO-LG", autocommit=True)
df = pd.read_sql(command,con)
print(df)
print(command)
writer = pd.ExcelWriter('Result.xlsx')
df.to_excel(writer, sheet_name='Test',index=False)
writer.save()
except:
print("Command skipped: ")
在代码中,我想用 python 为每个执行的 SQL 查询将工作表添加到现有的 excel 中。
基本上python不应该每次都替换我的excel
【问题讨论】: