简体   繁体   English

从word文档中提取表格

[英]Extracting tables from a word doc

Is there any tool to extract all tables from a word documents and converting them to a csv file or any excel extension file using python or vba是否有任何工具可以从 word 文档中提取所有表格并将它们转换为 csv 文件或任何 excel 扩展文件,使用 python 或 Z2E47AED18ABB27191

note that the word file contains both text and tables.请注意,word 文件包含文本和表格。

You can use pandas with python-docx .您可以将pandaspython-docx一起使用。 Per this answer you can extract all tables from a document and put them in a list:根据这个答案,您可以从文档中提取所有表格并将它们放在一个列表中:

from docx import Document
import pandas as pd
document = Document('test.docx')

tables = []
for table in document.tables:
    df = [['' for i in range(len(table.columns))] for j in range(len(table.rows))]
    for i, row in enumerate(table.rows):
        for j, cell in enumerate(row.cells):
            if cell.text:
                df[i][j] = cell.text
    tables.append(pd.DataFrame(df))

You can then save the tables to csv files by looping through the list:然后,您可以通过遍历列表将表保存到 csv 文件:

for nr, i in enumerate(tables):
    i.to_csv("table_" + str(nr) + ".csv")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM