Python-docx 复制栏

问题描述 投票:0回答:1

我想将列从一个表复制到另一个表。有什么办法可以做到吗?

enter image description here

我试过了,但没成功。

from docx import Document

doc = Document('document.docx')
table_one = doc.tables[0]
table_two = doc.tables[1]
column_table_one = table_one.columns[6]
column_table_two = table_two.columns[0]
column_copied = copy.deepcopy(column_table_one._gridCol)
gridCol = column_copied
column_table_two._gridCol.addprevious(gridCol)
python docx python-docx
1个回答
0
投票

添加新列后,需要移动到表格最左边(第一列)。

代码:

from docx import Document
from docx.shared import Inches

doc = Document('example.docx')
table_one = doc.tables[0]
table_two = doc.tables[1]

column_table_one = table_one.columns[-1]   # get the last column from table1
contents_to_copy = [cell.text for cell in column_table_one.cells] # copy the contents of the last column
new_column = table_two.add_column(Inches(1.0))  # add a new column, adjust the width as needed

# added column to the last
for cell in new_column.cells:   
    cell.text = contents_to_copy.pop(0)

# move the new column to the leftmost side
for i in range(len(table_two.columns) - 1, 0, -1):
    for cell1, cell2 in zip(table_two.columns[i].cells, table_two.columns[i - 1].cells):
        cell1.text, cell2.text = cell2.text, cell1.text

doc.save('example_updated.docx')

输出:

Column1 Column2 Column3 Column4 Column5 Column6 Column7
   1        2       3      4       5        6      7
  11       12      13     14      15       16     17


Column7 C1  C2
   7    21  23
  17    22  24
© www.soinside.com 2019 - 2024. All rights reserved.