pythonexcelindentationeofxlwings

EOF error with staticmethod for xlworkbook class


I'm trying to open password protected Excel workbooks and found the code I've posted below on this page but when I try to implement it I'm getting a SytaxError and an IndentationError.

xlpassword.py:

import xlwings as xw
from autoit.autoit import AutoItError
import autoit
import threading

class _WB(object):

  def __init__(self, path, password=None):
    self.path = path
    self.password = password
    self.name = path

  @staticmethod
  def _handlepassword(password):#this line is giving the error
    if password:
      autoit.win_wait_active("[TITLE:Excel]", 5)
      autoit.send(password)
      autoit.send("{ENTER}")


  def op(self):
    try: # If already opened
      autoit.win_activate("%s - Excel"%self.name)
      self.book = xw.Book(self.path)
    except AutoItError: # Else
      t = threading.Thread(target=self._handlepassword, args=(self.password,))
      t.start()
      self.book = xw.Book(self.path)
      t.join()
    finally:
      return self

  def _wait(self):
      autoit.win_wait_active("%s - Excel"%self.name, 1)

  def close(self):
      self._wait()
      self.book.close()
      autoit.win_close("Excel")

When I get to the def _handlepassword line I get the output

SyntaxError: unexpected EOF while parsing (, line 1)
IndentationError: unexpected indent (, line 1)

Which means when I import xlpassword.py into another python script, that new script fails to run

test_run.py:

import pandas as pd
from xlpassword import * #I know this isn't best practice

PATH = "C:\\Path\\to\\my\\file.xlsx"

print(PATH)
wb = _WB(path=PATH, password='MyP8ssw0rd')

I'm using python 3.8.1 on a windows 10 machine, and I have tried to run the code in spyder, sublime, and Rstudio (I normally work in Rstudio but I thought that might be what's causing the problem).

I have read up on classes, class methods, and static methods and I can't see what I'm doing wrong here so if anyone could provide assistance it would help a lot.


Solution

  • Since v0.16.1, xlwings supports opening of password protected workbooks out of the box:

    import xlwings as xw
    wb = xw.Book(password='mypassword')
    

    See also the API Reference: https://docs.xlwings.org/en/stable/api.html#xlwings.Book