使用python动态读取和/或覆盖excel文件,而不会出现覆盖警报

时间:2019-02-08 11:00:02

标签: python excel win32com bloomberg

由于某种原因,以下代码可以正常运行,但是即使我设置了xl.EnableEvents = False,文件覆盖警报仍然会出现,除非手动单击覆盖文件弹出窗口,否则该代码将不会进一步执行。有谁知道如何解决这一问题?

代码打开一个excel文件,该文件包含一个允许excel文件连接到Bloomberg api的字符串,我使用此解决方案here使其起作用。只要文件打开足够长的时间,数据就会被拉入文件,然后保存并退出。大约需要35秒才能获取数据,并且pandas表开始显示我所请求的内容

问题是弹出窗口! -我需要查看字符串'#N / A Requesting Data ...'何时不再存在于文件中,并且如果不定期保存文件,就无法找到一种方法。一个使我无需保存即可动态查看文件内容的解决方案将是很棒的。

解决方案here对我来说无法停止弹出窗口,我可能每次都可以制作一个新文件,然后最后将它们全部删除,但这似乎有些笨拙。如果有人想在更完整的上下文中查看代码和问题,则此问题扩展了此问题here

WB = 'C:/path/to/my/file.xlsx'
location = "EGLL"

def run_VWA(WB, location):
    """open the excel file, allow enough time to pull the data, then close and save"""

    bb = 'C:/blp/API/Office Tools/BloombergUI.xla'
    xl=win32com.client.DispatchEx("Excel.Application")  
    xl.Workbooks.Open(bb)
    xl.AddIns("Bloomberg Excel Tools").Installed = True

    wb = xl.Workbooks.Open(Filename=WB) #opens workbook in readonly mode.

    xl.Visible = False
    xl.EnableEvents = False
    xl.DisplayAlerts = False

    total=0
    colstring='#N/A Requesting Data...'
    while total < 40:
        wb.Save()   
        df = df_from_excel(WB, location)
        if colstring not in df:
            break
        time.sleep(3)
        total+=3


    wb.Close(SaveChanges=1)
    xl.DisplayAlerts = True
    xl.Quit()
    #Cleanup the com reference. 
    del xl   

    return

对此有任何帮助,我对win32com库的经验非常有限。

1 个答案:

答案 0 :(得分:1)

经过几个小时的挖掘,我发现了如何动态解决此问题而无需每次迭代都保存文件。如果还有其他人遇到此问题,则可以找到here的大多数解决方案。非常感谢assylias提供了一些有用的指示。

def run_VWA(WB, location):
    """open the excel file, allow enough time to pull the data, then close and save"""

    bb = 'C:/blp/API/Office Tools/BloombergUI.xla'
    xl=win32com.client.DispatchEx("Excel.Application")  
    xl.Workbooks.Open(bb)
    xl.AddIns("Bloomberg Excel Tools").Installed = True

    wb = xl.Workbooks.Open(Filename=WB) #opens workbook in readonly mode.

    xl.Visible = False
    xl.EnableEvents = False
    xl.DisplayAlerts = False

    count=0
    while True:
        readData = wb.Worksheets(location)
        allData = readData.UsedRange
        if allData.Rows.Count > 1 or allData.Columns.Count > 1:
            print('rows: {}'.format(allData.Rows.Count))
            print('cols: {}'.format(allData.Columns.Count))
            break
        print(wb)
        print(count)
        time.sleep(3)
        count+=3


    wb.Close(SaveChanges=1)
    xl.DisplayAlerts = True
    xl.Quit()
    #Cleanup the com reference. 
    del xl   

    return
相关问题