Python-docx 复制列

Python-docx Copy column

提问人:Jackp 提问时间:10/28/2023 最后编辑:mkrieger1Jackp 更新时间:10/29/2023 访问量:79

问:

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

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

评论


答:

0赞 Ömer Sezer 10/29/2023 #1

添加新列后,需要移动到表的最左侧(第一列)。将最右边的列移动到最左边的列是棘手的部分。我在示例.docx上进行了测试。

法典:

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

评论

0赞 Jackp 10/29/2023
如果列内容为图像,有没有办法复制带有图像的列,因为此代码仅适用于文本?
0赞 Ömer Sezer 10/29/2023
@Jackp是的,它仅适用于文本。