It's too niche, but I'll show you the problems and solutions when creating an Excel instance with xlwings.
Check below.
To create an Excel instance with xlwings, use xw.apps.add ()
or xw.App ()
. However, this method has the following problems.
--For some reason, the add-in does not load. --After closing the instant, opening the workbook from Explorer does not load the add-in.
If you open only Excel without opening the workbook (start it from the start menu), the add-in will load normally.
Create an Excel instance from the shell and pass it to xlwings without using xw.apps.add ()
or xw.App ()
.
import re
import subprocess
import time
from pathlib import Path
import xlwings as xw
def get_xl_path() -> Path:
#Function that returns the Excel installation path
subprocess_rtn = (
subprocess
.run(['assoc','.xlsx'], shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
.stdout.decode("utf8")
)
assoc_to = re.search('Excel.Sheet.[0-9]+', subprocess_rtn).group()
subprocess_rtn = (
subprocess
.run(['ftype', assoc_to], shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
.stdout.decode('utf-8')
)
xl_path = re.search('C:.*EXCEL.EXE', subprocess_rtn).group()
return Path(xl_path)
def xw_apps_add_fixed() -> xw.App:
#Function to create an Excel instance
xl_path = get_xl_path()
num = xw.apps.count
pid = subprocess.Popen([str(xl_path),'/e']).pid
#Wait until it can be recognized by xlwings
while xw.apps.count == num:
time.sleep(1)
#Wait until available from xlwings
while True:
try:
xw.apps[pid].activate()
break
except:
time.sleep(1)
return xw.apps[pid]
app = xw_apps_add_fixed()
--Change file extension association at Windows command prompt
Recommended Posts