How to refresh excel using python

2019-08-29 00:17发布

问题:

I need to evaluate a function within excel using python right after writing that function into excel with xlsx writer or openpyxl. I need to pull the number generated by this function back into python to use in a formula. I cannot calculate this number straight in python because it uses an excel function that was custom made to interact with another program. If I open the excel file after the function is written to a cell, the function evaluates.

I've tried using win32com but does not seem to work. Does anyone else know a way to accomplish this without using win32com?

回答1:

I figured it out. I didn't realize before that you can use win32com to write in excel as well.

import win32com.client as w3c

ex_file = w3c.DispatchEx('Excel.Application')
wb = ex_file.Workbooks.Add()
ws = wb.Worksheets.Add()
ws.Name = 'Test'
ws.Range('A1:A1') = <function>
wb.RefreshAll()
cell_val = ws.Range('A1:A1').value
print(cell_val)
wb.SaveAs(<file name.xlsx>)
ex_file.Quit()