且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解决pyinstaller不兼容python-docx的方法

更新时间:2021-10-03 19:21:11

需求

python-docx是一个python的读写word的库,可以用来读写word文档,向word文档里插入表格。例如如下的操作docx的代码:

from docx import Document
document = Document()
document.add_heading('Document Title', 0)
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')
document.add_paragraph(
    'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
    'first item in ordered list', style='List Number'
)
records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
)
table = document.add_table(rows=1, cols=3,style='Light Grid Accent 1')
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc
document.add_page_break()
document.save('demo.docx')

 

pyinstaller是python打包成exe的工具。

当我们要把编写好的使用了python-docx的程序打包时,问题来了。

首先,命令行打包

pyinstaller -D word_generate.py

这个没问题,word_generate.py是我的主程序文件。这里打包也不报错。但是下一步,运行的时候,duang~报错了,报错如下:

C:\lzw_programming\jira_test\dist\word_generate>word_generate.exe
Traceback (most recent call last):
  File "word_generate.py", line 4, in <module>
  File "site-packages\docx\api.py", line 25, in Document
  File "site-packages\docx\opc\package.py", line 116, in open
  File "site-packages\docx\opc\pkgreader.py", line 32, in from_file
  File "site-packages\docx\opc\phys_pkg.py", line 31, in __new__
docx.opc.exceptions.PackageNotFoundError: Package not found at 'C:\LZW_PR~1\JIRA_T~1\dist\WORD_G~1\docx\templates\default.docx'
[4232] Failed to execute script word_generate

解决方法

在翻了很多地方之后,终于找到了解决方法。很简单。增加一个hook-docx.py文件在PyInstaller\hooks目录下就可以了。下面是文件内容以及路径

#-----------------------------------------------------------------------------
# Copyright (c) 2018-2018, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
from PyInstaller.utils.hooks import collect_data_files
datas = collect_data_files("docx")

路径:解决pyinstaller不兼容python-docx的方法