Search code examples
excelgithubgithub-actionspywin32excel-interop

How to save an Excel file via COM interface in a github actions workflow


I've got a self-hosted windows runner and I try to run a workflow that executes a python script which creates an Excel file. The .yaml code of the workflow:

name: test
run-name: test
on: [push]
jobs:
  create-excel:
    runs-on: self-hosted
    steps:
      - name: Check out repository
        uses: actions/checkout@v3
      - name: Create excel
        run: python create_excel.py

The script creates an Excel document via COM interface (usage of COM is compulsory, I cannot switch to pandas / xlrd or other packages):

import os
import win32com.client as win32

excel = win32.Dispatch("Excel.Application")
workbook = excel.Workbooks.Add()
workbook.SaveAs(os.getcwd() + '\\Created.xlsx')
workbook.Close()
excel.Quit()

If I run the python script locally everything works fine. The workflow crashes though: it can create the Excel COM object and a new file, but the COM object then fails to save the File:

Traceback (most recent call last):
  File "C:\actions-runner\_work\TestRepo\create_excel.py", line 8, in <module>
    workbook.SaveAs(os.getcwd()+'\\Created.xlsx')
  File "<COMObject Add>", line 4, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'SaveAs method of Workbook class failed', 'xlmain11.chm', 0, -2146827284), None)

Solution

  • I managed to find the solution: you need to change DCOM settings for Excel:

    • Press Win+R, type dcomcnfg
    • Expand Component Services > My Computer > DCOM Config
    • Find Microsoft Excel > Properties (right click) > under the Identity tab set it to "The interactive user for background services".