Search code examples
pythonpython-docx

python-docx Copy Cell


I need to copy tables's cell with text and images to another table in another file.

# -*- coding: utf-8 -*-
from docx import Document

oldDocument = Document("d:/first.docx")

newDocument = Document()
temp = oldDocument.tables[9].rows[1].cells[1]
table = newDocument .add_table(rows=1, cols=1)
table.rows[0].cells[0] = temp
newDocument .save("d:/second.docx")

This is example of table

Пример

And this this Error TypeError: 'tuple' object does not support item assignment


Solution

  • You can't simply copy an object from one document to another. python-docx API objects are proxy objects, meaning they are a wrapper around the XML that actually constitutes the paragraph, cell, etc.

    You'll need to read the content from the source document, then create the required structure (like table, cells, paragraphs) in the target document, placing the content where it should go.

    You may be able to do something a little fancier if you go down to the lxml layer, perhaps copying the text with all its formatting (superscripts etc.), but that will require digging into the internals and understanding the underlying XML structure. If you search on 'python-docx workaround function' you should find some examples to get you started.