Python Loop to Create Sheets Using Openpyxl - python

I am trying to create a loop to add sheets to an excel file based on names in a list. For some reason it is not working. Would appreciate some help.
import openpyxl
worksheets = ['Balance Sheet Entries',
'Production Costs',
'Model - Realised',
'Orders',
'Manufacturing Comparison',
'Unit Economics']
# File where new sheets should be created
template = openpyxl.load_workbook('New File.xlsx')
#Loop through worksheets and create one new sheet using each name in the list.
for i in range(len(worksheets)):
template.create_sheet(worksheets[i]) #or template.create_sheet(title=worksheets[i])
The outcome of running this is exactly nothing. Nothing happens to the file and the code runs fine "Process finished with exit code 0".
Any help appreciated.

A quick scan through the docs suggests you need to call template.save(filename) in order to actually save to disk.

Related

Export data from MSSQL to Excel 'template' saving with a new name using Python

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.
Your method is work. The problem is you don't need to write the data into excel file right after you read the data from the database. My suggestion is first read the data into different data frame.
df1 = pd.read_sql(script)
df2 = pd.read_sql(script)
df3 = pd.read_sql(script)
You can then write all the dataframe together to a excel file. You can refer to this link.
I hope this solution can help you. Have a nice weekend

Refresh single worksheet (excel) in workbook using xlwings

I looked around a bit but could not find an answer. I found RefreshAll() which is not what I want to do.
Say I have a workbook named "DATA" with following sheets, "Forecast Temps", "Actual Temps", "Table", "Summary".
Now imagine that Forecast Temps sheet has a time series function that grabs data from NWS. This worksheet needs to be refreshed and then temps added into specified column in worksheet "Table". After this, Sheet Summary can be refreshed to determine new high and lows for that day.
Yes - I could run RefreshAll() at each step, but this seems redundant and would take the script longer to run. I was wondering if there was a way to refresh a single sheet w/ xlwings.
I also know you can do it in VBA, but my plan is to write a python script and then create a Sub where I call RunPython ("ScriptName").
Would I be able to do something like:
import xlwings as xw
wb = xw.Book("path")
forecast_temps = wb.sheet[0]
summary = wb.sheet[1]
forecast_temps.refresh() #do not know the correct func here (if there is one)?
I think RefreshAll() is not part of xlwings API. You may call the Excel API like this: wb.api.RefreshAll().
If you know how to do it in VBA, the same will probably work in xlwings using .api. I think you will have some kind of workbook connection. wb.api.Connections should return a list of all workbook connections. From there you can go on with the WorkbookConnection-Objects, which have a Refresh() method.

Touble with saving excel sheet/ making changes -- Python openpyxl

I am trying to automate the process of creating new cost sheets at my work.
I have a functional code that pulls the source file, renames it, moves it where I want it, etc.
I am trying to use openpyxl to write in some of the data that is parsed in creating the file/directory name. I can't posst my full ncode because it has work directories and such in it but here's the failing portion:
############################
#Write Info Into Cost Sheet#
############################
myworkbook=openpyxl.load_workbook(new_CSdst_file_name)
worksheet= myworkbook['COST SHEET']
worksheet['C3']= now.strftime("%m/%d/%Y")
worksheet['C5']='SOW-'+line_split[2]
worksheet['C6']='CS-'+line_split[4]
worksheet['C10']='0'
worksheet['J4']=line_split[3]
#myworkbook.save(new_CSdst_file_name)
If the save is commented out the file is created, but no cells are filled.
If I uncomment the save I get the attached excel error (see image)
Going home for the day, but any help appreciated. Will check in Monday!
Excel Error
Using #Greg 's comment I was able to find another answer that provided the solution.
Working code here:
myworkbook=openpyxl.load_workbook(new_CSdst_file_name, keep_vba=True)
worksheet= myworkbook['COST SHEET'] #Open Sheet Named COST SHEET (current Sheet 1 name in xlsm)
worksheet['C3']= now.strftime("%d-%b-%Y") #Date
worksheet['C5']='SOW-'+ PartNum #SOW number
worksheet['C6']='CS-'+ PartNum #CS number
worksheet['C7']= Description #descriptor
worksheet['C10']='0' #creating revision 0
worksheet['J4']= Customer #Company Name
myworkbook.save(new_CSdst_file_name)

How to put a value to an excel cell?

You'll probably laugh at me, but I am sitting on this for two weeks. I'm using python with pandas.
All I want to do, is to put a calculated value in a pre-existing excel file to a specific cell without changing the rest of the file. That's it.
Openpyxl makes my file unusable (means, I can not open because it's "corrupted" or something) or it plainly delets the whole content of the file. Xlsxwriter cannot read or modify pre-existing files. So it has to be pandas.
And for some reason I can't use worksheet = writer.sheets['Sheet1'], because that leads to an "unhandled exception".
Guys. Help.
I tried a bunch of packages but (for a lot of reasons) I ended up using xlwings. You can do pretty much anything with it in python that you can do in Excel.
Documentation link
So with xlwings you'd have:
import xlwings as xw
# open app_excel
app_excel = xw.App(visible = False)
# open excel template
wbk = xw.Book( r'stuff.xlsx' )
# write to a cell
wbk.sheets['Sheet1'].range('B5').value = 15
# save in the same place with the same name or not
wbk.save()
wbk.save( r'things.xlsx' )
# kill the app_excel
app_excel.kill()
del app_excel
Let me know how it goes.

Opening, writing, and modifying to an existing workbook using Python

I am new to Python and working on a project that I could use some help on. So I am trying to modify an existing excel workbook in order to compare stock data. Luckily, there was a program online that retrieved all the data I need and I have successful been able to pull the data and write the data into a new excel file. However, the goal is to pull the data and put it into an existing excel file. Furthermore, I need to overwrite the cell values in the existing file. I believe xlwings is able to do this and I think my code is on the right track, but I ran into an unexpected error. The error I get is:
com_error: (-2147352570, 'Unknown name.', None, None)
I was wondering if anyone knew why this error came up? Also, does anyone know how to fix it? Is it fixable? Is my code wrong? Any help or guidance is appreciated. Thank you.
import good_morning as gm
import pandas as pd
import xlwings as xw
#import income statement, balance sheet, and cash flow of AAPL
fd = gm.FinancialsDownloader()
fd_frames = fd.download('AAPL')
#Creates a DataFrame for only the balance sheet
df1 = pd.DataFrame(list(fd_frames.values())[0])
#connects to workbook I want to modify (this is where I get the commerror)
wb = xw.Book(r'C:/Users/vince/Project/Spreadsheet.xlsm')
#sheet I would like to modify
sht = wb.sheets[1]
#modifies & overwrites values in my spreadsheet
sht.range('M6').value = df1

Categories