python-docx使用document读取文件报错:docx.opc.exceptions.PackageNotFoundError: Package not found at

报错详情

在这里插入图片描述

原因

  • 执行到document=Document(word_path)时报错,python-docx模块无法读取该docx文件
def open_file(word_path,excel_path,excel_sheet_name):
    #打开word文档
    document=Document(word_path)
    tables=document.tables
    table_indexs=len(tables)
    #打开excel
    wb=openpyxl.load_workbook(excel_path)
    #打开表
    sheet=wb[excel_sheet_name]
    return tables,table_indexs,wb,sheet

解决办法

  • 找到win32comdoc转换为docx的代码
def doc_to_docx(path):
    if os.path.splitext(path)[1] == ".doc":
        word = client.Dispatch('Word.Application')
        doc = word.Documents.Open(path)  # 目标路径下的文件
        print("原始数据路径:"+os.path.splitext(path)[0])
        doc.SaveAs(os.path.splitext(path)[0]+".docx",16)  # 转化后路径下的文件
        try:
            print('保存文件')
            doc.Close()
            print('关闭Word.Application')
            word.Quit()
        except Exception as e:
            print(e)
  • doc.SaveAs(os.path.splitext(path)[0]+".docx",16)修改为如下代码
doc.SaveAs(os.path.splitext(path)[0]+".docx",12)
  • 转换格式有问题导致python-docx读取docx文件失败

疑问

  • 在另外一台电脑上,doc.SaveAs(os.path.splitext(path)[0]+".docx",16)转换的格式未出现问题
  • 在出问题的电脑上,使用doc.SaveAs(os.path.splitext(path)[0]+".docx",16)方式转换的docx可以使用wps正常打开

猜你喜欢

转载自blog.csdn.net/why123wh/article/details/106008068