Search code examples
pythondocxpython-docx

Python-docx Copy column


I'd like to copy column from a table to another. Is there any way to do it?

enter image description here

I've tried the following code, but the column is not copied.

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)

Solution

  • After adding a new column, it requires to move at the leftmost of the table (first column). Moving the rightmost column to the leftmost column is the tricky part. I tested on the example.docx.

    Code:

    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')
    

    Output:

    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