Save Excel operation is not properly done - python

I am using custom Excel library which is based on openpyxl module
Following are the keywords:
def open_excel(self, file):
self.filename = file
self.wb = openpyxl.load_workbook(self.filename)
def write_data_by_coordinates(self,sheetname,row_value, column_value,varValue):
self.sheet = self.wb.get_sheet_by_name(sheetname)
self.row = int(row_value)
self.column = int(column_value)
self.varValue = varValue
self.sheet.cell(row=self.row, column=self.column).value = self.varValue
def save_excel(self, file):
self.file = file
self.wb.save(self.file)
Using Robot Framework, I’m trying to write the values in excel and save it as below:
Write Data in Excel
Open Excel D:\\TestExcel.xlsx
Write Data By Coordinates Sheet1 1 1 Test1
Write Data By Coordinates Sheet1 1 2 Test2
Save Excel D:\\TestExcel.xlsx
After execution, I had opened the excel and verified it,the values are updated in excel.
When I tried to close the excel , it shows pop up as “Do you want to Save”?
Why is this pop-up shown when I did not edit/modify any value in excel sheet?
Is it not saved properly during execution by the keyword “Save excel” keyword?
I had even tried by adding the below line to the Save excel method in Custom library as
self.wb.close()
But still it shows the “Do you want to Save?” popup, when I open and close the excel sheet after test case execution.
Any suggestions would be helpful

I think this is just that the excel programme see changes it did not make and thus treats it like you did them at this time of its opening.
You could test this by making an excel file that has never been opened on your PC. Edit with the code and then open with excel.

Related

Python code not writing output in excel sheet but is able to take input from another sheet in same workbook

Background:
I am fetching Option chain for a symbol from web and then writing it to an excel sheet. I also have another excel sheet in the same workbook from which I take inputs for the program to run. All of this I am doing with excel 2016.
Sample of the code from program as the whole program is pretty long:
import xlwings as xw
excel_file = 'test.xlsx'
wb = xw.Book(excel_file)
wb.save()
# Fetching User input for Script/Ticker else it will be set to NIFTY as default
try:
Script_Input = pd.read_excel(excel_file, sheet_name = 'Input_Options', usecols = 'C')
script = Script_Input.iloc[0,0]
except:
script = 'NIFTY'
# Writing data in the sheet
sht_name = script + '_OC'
try:
wb.sheets.add(sht_name)
print('new sheet added')
wb.save()
except:
pass
# print('sheet already present')
# directing pointer towards current sheet to be written
sheet = wb.sheets(sht_name)
sheet.range('A4').options(index = False, header = False).value = df
sheet.range('B1').value = underlying
sheet.range('C1').value = underlying_Value
# sheet.range('A3').options(index = False, header = False).value = ce_data_final
# sheet.range('J3').options(index = False, header = False).value = pe_data_final
wb.save()
Problem: Since yesterday, I am able to open my excel workbook with excel 2016 and change inputs for my program but, I do not get any data written in the sheet that takes output from the program. The program runs perfectly as I can test the output on terminal. Also, once I delete the sheet no new sheet is being created as it should.
What I tried: I have uninstalled every other version of excel I had, so now only excel 2016 is present.
I have made sure that all the respective file formats use excel 2016 as the default app.
Also note that, 2 days ago I was able to write data perfectly in the respective sheet but now I am not able to do so.
Any help appreciated...
Sorry to everyone who tried to solve this question.
after #buran asked about 'df' I looked into my code and found that I had a return statement before writing 'df' into sheet (I have created a separate function to write data in excel). Now that I have moved that statement to its proper place the code is working fine. I am extremely sorry as I did not realise what the problem was in the 1st place and assumed it had to do with excel and python. Now the program runs perfectly and I am getting the output I want.

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.

Python OpenPyxl

I'm working with a large excel file(30MB+,xlsm). Many of them contain photos in cell comments, so this file takes up so much space. First im open a file to read and get specific column name. Im open that with:
self.wb = load_workbook(str(self.directory[0]), read_only=True, keep_vba=True, data_only=False)
self.ws = self.wb['BAZA_PRACOWNIKOW']
self.sheet = self.wb.active
After finding the appropriate cells, I open it again to add the relevant data to it:
self.wb = load_workbook(str(self.directory[0]), read_only=False, keep_vba=True, data_only=False)
self.ws = self.wb['BAZA_PRACOWNIKOW']
self.sheet = self.wb.active
When I complete this file I would like to save it, so:
self.wb.save('new.xlsm')
After that i got an error:
D:\Anaconda\lib\site-packages\openpyxl\reader\worksheet.py:310:
UserWarning: Data Validation extension is not supported and will be
removed warn(msg)
The file size after saving decrease to 8mb. All photos in comments are not in new.xlsm file.
Can someone help me ?
http://openpyxl.readthedocs.io/en/latest/usage.html
openpyxl does currently not read all possible items in an Excel file
so images and charts will be lost from existing files if they are
opened and saved with the same name.
Try lxlm or xlwings maybe?

Openpyxl crash excel file with table after save

I have created a basic workbook with one worksheet and in this worksheet I have created a table (Insert>Table). Nothing complex in this table, just the value 1, 2, 3 (and the column header of course).
I have written this simply code
import openpyxl
thefilename = r"C:\Users\Myfile.xlsx"
book = openpyxl.load_workbook(thefilename)
book.activesheet
book.save(thefilename)
Then, when I try to open the excel file, the file is corrupted and impossible to reopen it again.
This looks like a bug but I wonder how I can detect if my excel file has a table and how to remove it ?

How to write to an open Excel file using Python?

I am using openpyxl to write to a workbook. But that workbook needs to be closed in order to edit it. Is there a way to write to an open Excel sheet? I want to have a button that runs a Python code using the commandline and fills in the cells.
The current process that I have built is using VBA to close the file and then Python writes it and opens it again. But that is inefficient. That is why I need a way to write to open files.
If you're a Windows user there is a very easy way to do this. If we use the Win32 Library we can leverage the built-in Excel Object VBA model.
Now, I am not sure exactly how your data looks or where you want it in the workbook but I'll just assume you want it on the sheet that appears when you open the workbook.
For example, let's imagine I have a Panda's DataFrame that I want to write to an open Excel Workbook. It would like the following:
import win32com.client
import pandas as pd
# Create an instance of the Excel Application & make it visible.
ExcelApp = win32com.client.GetActiveObject("Excel.Application")
ExcelApp.Visible = True
# Open the desired workbook
workbook = ExcelApp.Workbooks.Open(r"<FILE_PATH>")
# Take the data frame object and convert it to a recordset array
rec_array = data_frame.to_records()
# Convert the Recordset Array to a list. This is because Excel doesn't recognize
# Numpy datatypes.
rec_array = rec_array.tolist()
# It will look something like this now.
# [(1, 'Apple', Decimal('2'), 4.0), (2, 'Orange', Decimal('3'), 5.0), (3, 'Peach',
# Decimal('5'), 5.0), (4, 'Pear', Decimal('6'), 5.0)]
# set the value property equal to the record array.
ExcelApp.Range("F2:I5").Value = rec_array
Again, there are a lot of things we have to keep in mind as to where we want it pasted, how the data is formatted and a whole host of other issues. However, at the end of the day, it is possible to write to an open Excel file using Python if you're a Windows' user.
Generally, two different processes shouldn't not be writing to the same file because it will cause synchronization issues.
A better way would be to close the existing file in parent process (aka VBA code) and pass the location of the workbook to python script.
The python script will open it and write the contents in the cell and exit.
No this is not possible because Excel files do not support concurrent access.
I solved this doing the follow: Create an intermediary excel file to recieve data from python and then create a connexion between this file and the main file. The excel has a tool that allow automatically refresh imported data from another workbook. Look this LINK
wb = openpyxl.load_workbook(filename='meanwhile.xlsm', read_only=False, keep_vba=True)
...
wb.save('meanwhile.xlsm')
In sequence open your main excel file:
On the Data tab, create a connexion with the "meanwhile" workbook, then in the Connections group, click the arrow next to Refresh, and then click Connection Properties.
Click the Usage tab.
Select the Refresh every check box, and then enter the number of minutes between each refresh operation.
Using below code I have achieved, writing the Excel file using python while it is open in MS Execl.
This solution is for Windows OS, not sure for others.
from kiteconnect import KiteConnect
import xlwings as xw
wb = xw.Book('winwin_safe_trader_youtube_watchlist.xlsx')
sht = wb.sheets['Sheet1']
stocks_list = sht.range('A2').expand("down").value
watchlist = []
time.sleep(10)
for name in stocks_list:
symbol = "NSE:" + name
watchlist.append(symbol)
print(datetime.datetime.today().time())
data = kite.quote(watchlist)
df = pd.DataFrame(data).transpose()
df = df.drop(['depth', 'ohlc'], 1)
print(df)
sht.range('B1').value = df
time.sleep(1)
wb.save('winwin_safe_trader_youtube.xlsx')

Categories