Search code examples
excelpywin32xlwings

Is there a way to calculate a particular sheet in excel using python?


I need to calculate a sheet of interest in excel using python. There is a method to calculate the entire workbook using the following code.

import xlwings as xw
book = xw.Book(file_path)
book.app.calculate()

Is there a way to accomplish the same for a single sheet? Tried

book.sheets["Sheet 1"].calculate

but sheet object has no "calculate" attribute.

Edit. Tried the following too.

import win32com.client 
xl = win32com.client.gencache.EnsureDispatch("Excel.Application")
wb = xl.Workbooks.Open(file_path)
wb.Worksheets('Page 2').Calculate()

This doesn't give any error but doesn't work either.

Edit-2 Found the answer finally, been missing "EnableCalculation = True. "

import win32com.client 
xl = win32com.client.gencache.EnsureDispatch("Excel.Application")
wb = xl.Workbooks.Open(file_path)
ws = wb.Worksheets('Page 2')
ws.EnableCalculation = True 
wb.Worksheets('Page 2').Calculate()

Solution

  • There was a similar question here. The solution (for now) is to use api.Calculate(), so you don't need to enable calculations to do this.

    So in your second example code, you could instead run:

    wb.sheets["Sheet 1"].api.Calculate()