如何在 python 中连接 docx 文件?

How to concat docx file in python?

下面是我的代码:

 v_excel= []
 for root, dirs, files in os.walk(paths):
     for t in files:
         if t.endswith('.xlsx'):   
             df = pd.read_excel(os.path.join(paths,t), header=None, index_col=False)
             v_excel.append(df)

conc = pd.concat(v_excel, axis=1, ignore_index=True)    

conc 输出:

#after appending two excel files i can successively concat the files and put it in 
#seperate column

column1   column2
data1     data1 
data2     data2
data3     data3
data3     data4

#column 1 is from excel file 1 and column2 from excel file 2

如何像我对 excel 那样对 docx 执行此操作?

if t.endswith('.docx'):
    #for c,z in enumerate(t):
        v_doc.append(Document(t))  # <-----how to put this in df and concat according to 
                                   #       docx file as i have done with excel ?

docx 包含: #docx 包含虚拟文本的 !!!

#docx1 contains:
   
data1
data2
data3
data4

#docx2 contains:
   
data5
data6
data7
data8

我想将 docx 文件的内容保存到 excel 的列中。 docx 1 内容到 excel 的第 1 列,docx 2 到相同 excel.

的第 2 列

希望我能得到一些回应。提前谢谢你。

解决方案 #1: 将多个 .docx 文档聚合为单个输出 docx 文档。

如果想将文本和样式从一组 docx 文档复制到单个输出 docx,则可以使用 python-docx 模块。

from docx import Document
import os

master = Document()
for f in os.listdir('.'):
    if f.endswith('.docx'):
        doc = Document(f)
        for p in doc.paragraphs:
            out_para = master.add_paragraph()
            for run in p.runs:                
                output_run = out_para.add_run(run.text)
                # copy style from old to new
                output_run.bold = run.bold
                output_run.italic = run.italic
                output_run.underline = run.underline
                output_run.font.color.rgb = run.font.color.rgb
                output_run.style.name = run.style.name

master.save('out.docx')

解决方案 #2: 将多个 .docx 文档中的 table 内容聚合到单个输出 excel 文档。

在您的评论中,您想从一组包含 table 文本的 word 文档创建 excel sheet。

这里是 Python 代码,用于将 table 的 Word 文档中的单元格复制到目标 Excel 文档。

import pandas as pd
from docx import Document
import os

df = None
for f in os.listdir('data'):
    if f.endswith('.docx'):
        doc = Document(file)
        for table in doc.tables:
            for row in table.rows:
                data = []
                for cell in row.cells:
                    data.append(cell.text)               
                if df is None:
                    df = pd.DataFrame(columns=list(range(1, len(data)+1)))
                df = df.append(pd.Series(data, index=df.columns),
                               ignore_index=True)

df.to_excel("output.xlsx")

解决方案 #3: 将来自多个 .docx 文档的自定义 table 内容聚合到具有 2 列的单个输出 excel 文档 table.

在您的特定示例数据中,table 由 3 列或 9 列组成,因此如果要在输出中保留 2 列,则需要将其他列的文本连接成一个值。

df = None
for f in os.listdir('data'):
    if f.endswith('.docx'):
        doc = Document(file)
        # iterate over all the tables
        for table in doc.tables:
            for row in table.rows:
                cells = row.cells
                if len(cells) > 1:
                    col1 = cells[0].text
                    # check if first column is not empty
                    if col1:
                        # concatenate text of cells to a single value
                        text = ''
                        for i in range(1, len(cells)):
                            if len(text) != 0:
                                text += ' '
                            text += cells[i].text
                        data = [cells[0].text, text]
                        if df is None:
                            df = pd.DataFrame(columns=['column1', 'column2'])
                        df = df.append(pd.Series(data, index=df.columns),
                                 ignore_index=True)
# save output
df.to_excel("output.xlsx")

您可以 docxcompose 连接 python 中的 docx 文件。您可以在 docxcompose's pypi official page

中阅读更多说明