批量读取word文档里的表格信息并将其输出为excel表格

1、读取文件夹下的所有文件,并过滤出.doc文件(因为python依赖包docx只能打开.docx文件,需要先过滤出.doc文件将其转为.docx)

import os

def list_files_doc(path):
    files_doc = []
    for i, j, k in os.walk(path):
        for file in k:
            suffix = file.split('.')
            if suffix[1] == 'doc':
                print(file)
                files_doc.append(os.path.join(path, file))

    print('doc格式的文件列表:{}'.format(files_doc))
    return files_doc


if __name__ == '__main__':
    list_files_doc('E:\\python_myfile\\read_excel')

 

2、将.doc文件转为.docx文件

from win32com import client as wc  # 导入模块

def doc2docx(doc_files):
    word = wc.Dispatch("Word.Application")  # 打开word应用程序
    for doc_file in doc_files:
        doc = word.Documents.Open(doc_file)  # 打开word文件
        doc.SaveAs("{}x".format(doc_file), 12)  # 另存为后缀为".docx"的文件,其中参数12指docx文件
        doc.Close()  # 关闭原来word文件
    word.Quit()
    print("doc文件转docx完成")

if __name__ == '__main__':
    doc2docx(['E:\\python_myfile\\read_excel\\用户1信息.doc',])

 

 

3、从.docx文件读取表格信息

from docx import Document
import os

def get_data_from_docx_files(path):
    print(path)
    data = []
    for i, j, k in os.walk(path):
        for file in k:
            suffix = file.split('.')
            if suffix[1] == 'docx':
                document = Document(file)  # 读入文件
                tables = document.tables  # 获取文件中的表格集

                table = tables[0]
                name = table.cell(0, 1).text
                sex = table.cell(0, 3).text
                info = {"name": name, "sex": sex}
                print(info)
                data.append(info)
    return data

if __name__ == '__main__':
    get_data_from_docx_files('E:\\python_myfile\\read_excel')

 

4、将信息输出excel表格

import xlwt

def output_excel(header, data, result_excel):
    # 读取文本文件
    book = xlwt.Workbook(encoding='utf-8', style_compression=0)  # 创建一个Workbook对象,这就相当于创建了一个Excel文件
    sheet = book.add_sheet('test', cell_overwrite_ok=True)  # # 其中的test是这张表的名字,cell_overwrite_ok,表示是否可以覆盖单元格,其实是Worksheet实例化的一个参数,默认值是False

    # 写入表头
    i = 0
    for k in header:
        sheet.write(0, i, k)
        i = i + 1

    # 写入内容
    row = 1
    for val in data:
        print(val)
        sheet.write(row, 0, val['name'])  # 第二行第一列
        sheet.write(row, 1, val['sex'])  # 第二行第二列
        row = row + 1

    book.save(result_excel)

if __name__ == '__main__':
    output_excel(['姓名', '性别'], [{'name':'Danny', 'sex': 'female'}, {'name':'Merry', 'sex': 'male'}], '结果.xls')

 

posted @ 2022-02-28 15:09  DoubleFishes  阅读(1243)  评论(0编辑  收藏  举报