3

I'm trying to automate some things with python, one of the steps is opening the .xlsx file using the "win32com.client" module and then printing a few sheets into PDF. It all works fine if I have the file already opened in Excel, but if the Python script wants to open it, Excel asks me to set a different name for "_FilterDatabase" and "Print_Area", even though I can open it manually with no issues.

If I do change the names, then I have to set all the print areas again. Saving the file with new print areas causes the same issue. I don't have any idea why opening the file with win32com is different than opening it manually.

Here's the simple code, just for opening the file:

import win32com.client

wb_path = r'D:\Users\Agenerick\Documents\Projects\sprawozdania-gen\excel\a.xlsx'
o = win32com.client.Dispatch("Excel.Application")
o.Visible = True
o.Workbooks.Open(wb_path)

I've tried using the ReadOnly flag and xlwings, even using ComObject in Powershell, no difference, however, opening the file using subprocess went fine, but then I can't really hide the window. I also don't have any other versions of Excel installed.

Agen
  • 63
  • 5
  • Where and when do you run the code? – Eugene Astafiev Mar 09 '21 at 05:57
  • I don't really know how to answer when because this issue also happens when I try to use $objExcel = New-Object -ComObject Excel.Application in powershell at any point in time, and the file is stored in my documents folder, so I doubt it's about permissions. – Agen Mar 09 '21 at 12:20

1 Answers1

1

Friend helped me with it and found a post in German with a similar bug. The way I fixed it is I replaced o.Workbooks.Open(wb_path) with o.Workbooks.OpenXML(wb_path)

Apparently it's a bug with Excel. After that I also had to change wb.Worksheets.Select() (or something similar) to wb.Sheets.Select()

Agen
  • 63
  • 5