Python script to select the already opened excel file - python

I have a nice python script for refreshing of an excel file. What it does is it opens the excel file, refreshes it, saves and then closes.
But now I want to change this -
I want to open the excel file(s) manually, and then the python script should choose the particular already opened excel file(s) on the taskbar, should refresh it and save it but not close it. The action should repeat again in 1 hour.
Can anyone help me.
Here is my current script
import win32com.client as win32
import time
xlapp = win32.DispatchEx('Excel.Application')
wb = xlapp.Workbooks.Open('Excel path')
xlapp.visible = True
wb.RefreshAll()
time.sleep(10)
wb.Save()
wb.Close()
xlapp.Quit()

Related

Returning the python Script from particular line

How Can i loop back the python script from particular line. This is about the refreshing an excel and I want to refresh it once in 2 hours.
import win32com.client as win32
import time
xlapp = win32.DispatchEx('Excel.Application')
wb = xlapp.Workbooks.Open('Excel path')
xlapp.visible = True
wb.RefreshAll()
time.sleep(10)
wb.Save()
wb.Close()
xlapp.Quit()
I don't want to close the excel file. So basically save it and loop back again after 2 hours and refresh and save... Repeat
How can I don that?
Since you've already imported time, you could build a loop with time.sleep(7200) (7200 seconds being two hours) that keeps saving. Although I don'T think it's a good idea to keep the file open throughout that time. What speaks against closing and re-opening it after two hours?

How to ignore "Enable Editing" in excel after writing data using openpyxl

I am using a Excel template which have 6 tabs (All unprotected) and writing the data on each worksheet using openpyxl module.
Once the excel file is created and when tried to open the generated file, its not showing all data untill and unless I click "Enable editing" pop up.
Is there any attribute to disable in openpyxl.
This sounds like Windows has quarantined files received over a network. As this is done when the files are received, there is no way to avoid this when creating the files.
I solved this for me.
I found the answer here:
https://codereview.stackexchange.com/questions/240136/python-script-for-refreshing-and-preprocessing-data-in-excel-report-files
I only used the refresh function and it basically opened the excel file, click/refreshed, and closed/saved. You see an Excel file appear briefly on the screen. I'll insert this in a loop to go through all the files I am creating. It might take a little while to run hundreds, but much faster than open-click-save.
Here is all the code I used:
import win32com.client as win32
def refresh(directory, file_name):
xlapp = win32.DispatchEx('Excel.Application')
xlapp.DisplayAlerts = False
xlapp.Visible = True
xlbook = xlapp.Workbooks.Open(directory + '\\' + file_name)
xlbook.RefreshAll()
xlbook.Save()
xlbook.Close()
xlapp.Quit()
return()

Can't detect if the excel file is open without prompting user to save file / cancel

Using Iron Python I need to first determine if the excel file is already open and then if it is open, access it. if its not open then open it. problem: in my try statement when I try to open the workbook if its already open instead of failing the try it completes it instead and prompts the user to save / cancel the open file in excel. I want it to fail the try if the excel file is already open not prompt the user.
I use the Marshal Interopt lib to access the open file and that works well
UserExcelFile = os.path.join(userdirectory, 'podi.xlsx')
try:
workbook = excel.Workbooks.Open(UserExcelFile)
except:
print "Looks like it was already open"
return
workbook = excel.ActiveWorkbook
ws = excel.ActiveSheet
If the file is already open "workbook = excel.ActiveWorkbook" works perfect to edit the already open excel file.
I don't think your try except statement is going to catch an exception here. The line below will open the same file again even if it is already open.
workbook = excel.Workbooks.Open(UserExcelFile)
You should check if the file is already open yourself. Suggestions on how it can be done can be found here on stack: Python: Open Excel Workbook using Win32 COM Api
I finally got this working to where it will check using interop if the excel file is already open, if its not, it will open and start.. if it is already open then it just starts editing the open workbook. This is only a big deal for me because its Iron Python and the Win32 COM Api will not work with Iron.
if ex.Workbooks.Open(UserExcelFile) == True:
ExtAPI.Log.WriteMessage("excel file already open")
workbook = excel.ActiveWorkbook
ex = workbook
ws = excel.ActiveSheet
else:
workbook = ex.Workbooks.Open(UserExcelFile)
ws = workbook.Worksheets[1]

How can I check if a specific workbook (Excel file) is opened? After I find out, how can I close it?

I created a Python script which scrapes a website, grabs the information I need and writes it in an Excel file. The problem is that, sometimes, after I check what has been written, I forget to close the Excel file and the script no longer runs (due to the fact that the file is already opened)
To open/write/save/close the Excel file, I am using the openpyxl library, but I don't know how to check if that specific file is opened and how to close it afterwards.
#writing to excel
pathexcel = r'C:\Users\...\Data.xlsx'
wb = load_workbook(pathexcel)
sheet = wb.active
sheet.append(row1)
sheet.append(row2)
sheet.append(row3)
wb.save(pathexcel)
Thank you!

Open excel safe mode win32com - python 2.7

I am running a program using python with would open a macro enabled excel file that uses COM objects to capture the real time data from an application. I frequently end up in an Excel crash error (occurs when i run the job more than two or three times). I went through web and found that this might be due to add ins that are installed to my excel file, I followed the instructions to remove the add ins from excel but still have the problem. I am using win32com to open the excel file and here is the code that I am using. I am new to python, please share your comments to improve this code and fix this issue.
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(excel, r'C:\\pynow_futu.xlsm')
win32api.Sleep(5000)
ws = wb.Worksheets('fut')
excel.Visible = True
excel.DisplayAlerts = False
for wb in excel.Workbooks:
ws = wb.Worksheets('fut')
if wb.Name == 'pynow_futu.xlsm':
print("WB:", str(wb.Name))
wb.DoNotPromptForConvert = True
wb.CheckCompatibility = False
filename = "C:\\futu.csv"
win32api.Sleep(2000)
wb.SaveAs(filename,FileFormat=24, ConflictResolution=2)
win32api.Sleep(1000)
wb.Close(True)
The excel file got crashed because few child process from the previous run was still active and it stops from opening the new file thus it crash. Fixed it by killing the child process

Categories