I am racking my brain here and have read a lot of tutorials, sites, sample code, etc. Something is not clicking for me.
Here is my desired end state.
- Select data from MSSQL - Sorted, not a problem
- Open an Excel template (xlsx file) - Sorted, not a problem
- Export data to this Excel template and saving it with a different name - PROBLEM.
What I have achieved so far: (this works)
- I can extract data from DB.
- I can write that data to Excel using pandas, my line of code for doing that is:
pd.read_sql(script,cnxn).to_excel(filename,sheet_name="Sheet1",startrow=19,encoding="utf-8")
- filename variable is a new file that I create every time the for loop runs.
What my challenge is:
- The data needs to be export to a predefined template (template has formatting that must be present in every file)
- I can open the file and I can write to the file, but I do not know how to save that file with a different name through every iteration of the for loop In my for loop I use this code:
#this does not work
pd.read_sql(script,cnxn)
writer = pd.ExcelWriter(SourcePath) #opens the source document
df.to_excel(writer)
writer.save() #how to I saveas() a different file name?????
Your help would be highly appreciated.