My code is reading SQL queries from text file and executing them one by one in python.I am trying save result of queries in the same excel but in different tabs/worksheets
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: ")
In the code I want to python to add sheets to existing excel for each SQL queries executed.
Basically python should NOT replace my excel every time