Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update an Excel sheet in real time using Python

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.

like image 512
West Avatar asked May 18 '18 12:05

West


2 Answers

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
like image 76
West Avatar answered Sep 19 '22 07:09

West


You've already worked out why you can't use openpyxl to write to the .xlsx file: it's locked while Excel has it open. You can't write to it directly, but you can use win32com to communicate with the copy of Excel that is running via its COM interface.

You can download win32com from https://github.com/mhammond/pywin32 .

Use it like this:

from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
wb=xlApp.Workbooks.Item("MyExcelFile.xlsx")
ws=wb.Sheets("MyWorksheetName")

At this point, ws is a reference to a worksheet object that you can change. The objects you get back aren't Python objects but a thin Python wrapper around VBA objects that obey their own conventions, not Python's.

There is some useful if rather old Python-oriented documentation here: http://timgolden.me.uk/pywin32-docs/contents.html

There is full documentation for the object model here: https://msdn.microsoft.com/en-us/library/wss56bz7.aspx but bear in mind that it is addressed to VBA programmers.

like image 40
BoarGules Avatar answered Sep 19 '22 07:09

BoarGules