[Python] pywin32: Word.Documents.Open(filename) wants a string, how can I give it a BytesIO...

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    The function win32com.client.gencache.EnsureDispatch('Word.Application').Documents.Open() wants a filename as input, to open an existing word doc. I have a doc created in memory with docx and would like to open it directly, probably as a BytesIO. I've spent some time with the pywin32 docs, and the generated source code Documents.py is no help to me.

    Here's an example of what currently works:

    import win32com.client as win32
    from docx import Document

    doc = Document()
    doc.save(path_to_file)

    word = win32.gencache.EnsureDispatch('Word.Application')
    word.Documents.Open(path_to_file)


    And here is the pattern I would prefer to use:

    import win32com.client as win32
    from docx import Document
    import io

    doc = Document()
    docstream = io.BytesIO()
    doc.save(docstream)

    word = win32.gencache.EnsureDispatch('Word.Application')
    word.Documents.Open(docstream)


    However, this results in an error: pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 16)

    How can I get a bytestream into word.Documents?

    Continue reading...

Compartilhe esta Página