Update an Excel sheet in real time using Python

West picture West · May 18, 2018 · Viewed 17.1k times · Source

Is there a way to update a spreadsheet in real time while it is open in Excel? I have a workbook called Example.xlsx which is open in Excel and I have the following python code which tries to update cell B1 with the string 'ID':

import openpyxl

wb = openpyxl.load_workbook('Example.xlsx')
sheet = wb['Sheet']
sheet['B1'] = 'ID'

wb.save('Example.xlsx')

On running the script I get this error:

PermissionError: [Errno 13] Permission denied: 'Example.xlsx'

I know its because the file is currently open in Excel, but was wondering if there is another way or module I can use to update a sheet while its open.

Answer

West picture West · May 19, 2018

I have actually figured this out and its quite simple using xlwings. The following code opens an existing Excel file called Example.xlsx and updates it in real time, in this case puts in the value 45 in cell B2 instantly soon as you run the script.

import xlwings as xw

wb = xw.Book('Example.xlsx')
sht1 = wb.sheets['Sheet']
sht1.range('B2').value = 45