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

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)

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

Python Loop to Create Sheets Using Openpyxl

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.

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.

Reading cell value without redefining it with Openpyxl

I need to read this .xlsm database and some of the cells values I need are derived from Excel functions. To accomplish this I used:
from openpyxl import load_workbook
wb = load_workbook('file.xlsm', data_only=True, keep_vba=True)
ws = wb['Plan1']
And then, for every cell I wanted to read:
ws.cell(row=row, column=column).value
This works fine for getting the data out. But the problem comes with saving. When I do:
wb.save('file.xlsm')
It saves the file, but all the formulas inside the sheets are lost
My dilemma is reading the cell's displayed values on one of the database's sheet without modifying them, writing the code's output in a new sheet and saving it.
Read the file once in read-only and data-only mode to look at the values and another time keeping the VBA around. And save under a different name.

Add data to existing excel file using python

I am trying to add data to an existing excel file, the problem I am facing is that the data is getting imported but the equation and the format is being deleted in original file.
I attached my code below
import xlwt
import xlrd
from xlutils.copy import copy
#open the excel file
rb=xlrd.open_workbook('Voltage_T.xlsx')
#make a writable copy of the opened excel file
wb=copy(rb)
#read the first sheet to write to within the writable copy
w_sheet=wb.get_sheet(0)
#write or modify the value at 2nd row first column
w_sheet.write(0,1,'WWW.GOOGLE.COM')
#the last step saving the work book
wb.save('Voltage_WW.xls')
You need to set formatting_info to true
rb=xlrd.open_workbook('Voltage_T.xlsx', formatting_info = True)
However xlrd doesn't support xlsx with formatting_info at the moment. So if you really have to use .xlsx you will need another library.
I didn't used it myself so I can't tell you if it's a good library but thanks to a quick search on google XlsxWriter seems to answer your needs.

Categories