Returning the python Script from particular line - python

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?

Related

Python open and save Excel file. Do I need to state sleep time?

My Excel file when opened will need 30 seconds to load data from a database.
My script below successfully Open, Wait till data fully loaded then Save and Close Excel file one by one.
So my question is: Does python by default must wait till the workbook is fully load before it move to the next command Save(). And then wait until Save() is completed to execute Close().
I don't mind to put time.sleep(10) but I want to know how python processes the command sequence in this case.
(When I do parsing data from web, I need to command Python to wait for a certain element is loaded. That's why I wonder if I need to instruct Python to do the same with Excel.)
files = ['file1','file2']
path = f'C:\\Users\\Myfolder\\'
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True
for i in files:
print(i)
wb = excel.Workbooks.Open( path + str(i)+'.xlsx')
# time.sleep(25)
for wb_name in excel.Workbooks: #list all currently open excel file
if wb_name.Name == str(i)+'.xlsx' : #Save exact file name
print("Save workbook:",wb_name.Name)
wb_name.Save()
wb_name.Close()
No python by default do not wait till the workbook is fully load before it move to the next command Save(). And rushes to the next before Save() is completed to execute Close(). THerefore, I recommend you to put delay time. Usually, the sleep time demands on the machine processing speed. In your case, it should time.sleep(35). The extra five second is just for safety.
for i in files:
print(i)
wb = excel.Workbooks.Open( path + str(i)+'.xlsx')
time.sleep(35) # yes you need it. Otherwise error message will come out.

Python script to select the already opened excel file

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()

Excel display Alerts despite Application.DisplayAlerts = False

I have a python script that every morning opens an excel file, refreshes it and saves as new file with todays date. Even though no changes occur between the .SaveAs and .Close and despite all precausions taken to not display save prompt, excel of course display a dialog prompting me to save or not before close. And to make this a bit more interesting, this doesn't happen every time, sometimes it can run for weeks without it happening, and then one day it just doesn't work.
Code sample:
import os
import datetime
import win32com.client as win32
from pywinauto.application import Application
# set todays date
dt = datetime.date.today()
# connect to Excel instance
xl = win32.dynamic.Dispatch("Excel.Application")
# open the excel template
wb = xl.Workbooks.Open([path to excel file])
# set report name
report_name = "Pending Report - INTERNAL - " + str(dt) + ".xlsx"
# refresh data
wb.RefreshAll()
# save as new file with todays date
wb.SaveAs(os.path.normpath(path + report_name))
# set excel not to display alerts - to not prompt for save before close
xl.DisplayAlerts = False
# disable Events - to not prompt for save before close
xl.EnableEvents = False
# set state of workbook to Saved to make sure excel sees the file as saved
xl.Workbooks(report_name).Saved = True
# close file and save changes set to true, ie. save the changes upon close
xl.Workbooks(report_name).Close(SaveChanges=1)
# looks for the save prompt - but the code never gets here, it halts on previous line waiting for input on dialog window
try:
app = Application(backend="uia").connect(title_re=".*Workbook Before Close*")
txt = app[u"Dialog"][u"Static"].window_text()
if "Do you want to save the changes you made" in txt:
app[u"Dialog"].YesButton.click()
except:
log("l", "i", "Didn't find excel or dialog window, might not be an issue but the Save dialog check wasn't successful")
Anyone have any ideas, or know what I'm doing wrong here?
Just to be fully clear, I've tested different combinations of these xl.DisableEvents etc. also tried them separately, some seem to work for a while then one day suddenly it doesn't anymore. Since this is an automated scheduled task, when it halts, it just sits there until I get an angry email asking for the report.
Now I know a workaround would be to create another scheduled task that runs another py file, that checks for the dialog, but that's not the issue here, what I want to get working is excel to do as instructed - i.e. not displaying the save before close prompt.
Thanks everyone.
Try the following:
xl = win32.gencache.EnsureDispatch('Excel.Application')

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()

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