[Python] Manually Copying Chart from Docx to Another Results in Corrupted File

Discussão em 'Python' iniciado por Stack, Janeiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a requirement to copy content from a docx file and append it to another, but the mess starts when it comes to charts.

    I'm using python-docx, and since it does not support charts natively, here's what I do:

    1. get the run's xml of the chart from document.xml
    2. find the related chart.xml part and the respective rId
    3. add the chart.xml to the target docx as a new part and get a new rId
    4. replace the rId in the xml of step1, then append it to the document.xml of the target docx
    5. add parts related by chart.xml to the target docx, and update chart.xml with the new rIds

    psuedo code:

    from docx import Document
    from docx.oxml import parse_xml

    chart_doc = Document("chart.docx")
    target_doc = Document("target.docx")

    for paragraph in chart_doc.paragraphs:
    new_para = target_doc.add_paragraph()

    for run in paragraph.runs:
    run_xml = run.get_xml()

    chart_rid = extract_rid(run_xml)
    rel = get_rel_by_id(chart_rid)
    chart_part = rel.target_part

    new_part = create_part(chart_part)
    new_rid = target_doc.relate_to(new_part, rel.reltype)

    if has_relationships(rel.target_part):
    rids = add_related_parts(chart_part, target_doc)
    new_part.blob = replace_rids_in_xml(new_part.content, rids).encode()

    new_run = parse_xml(run_xml)
    new_para.append(new_run)
    target_doc.save("target_modified.docx")


    The problem is, the modified docx could not be opened by Word:
    target_modified.docx

    I tried validating it with Open XML Productivity Tool, there are 2 errors but I don't think they are relavant.
    (it reports the same errors to a normal docx file containing charts as well)

    [​IMG]

    [​IMG]

    So, I'd like to know what is the problem of the result file, and what parts I'm missing here, thanks.

    sharing all 3 docx files here: py_docx

    I know this feature might come with some perfect commercial libs but it doesn't seem to be an option for me at the moment:)

    Continue reading...

Compartilhe esta Página