Use python to link excel with word document

Viewed 26

I have written a script to link an excel spreadsheet to a word document using xlwings, python docx and docxtpl. The source excel spreadsheet in question is found using the .caller() method which references the calling excel book through a macro referencing the script. Please find this script below:

import os, sys, glob, datetime
import xlwings as xw
from docxtpl import DocxTemplate
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH

os.chdir(r'C:\Users\bena\Documents\demo\Placeholder_Words')

## set up folder locations
input_dir = r'C:\\Users\\bena\\Documents\\demo\\Placeholder_Words\\'
output_dir = r'C:\\Users\\bena\\Documents\\demo\\Placeholder_Words\\'

def main():
    wb = xw.Book.caller()
    sht_panel = wb.sheets['PANEL']
    doc = DocxTemplate('See_Houses_Template_Report.docx')
    # -- Get Values from Excel in to a dictionary ↓ expand = table dynamically picks up the table in excel rather than specifically typing it out.
    context = sht_panel.range('A1').options(dict, expand='table', numbers=int).value

    # -- Render & Save Word Document
    output_name = 'Final_Report.docx'

    Excel = True
    if Excel: 
            ## loop through graphs and save as a picture 
            i = 0    
            for chart in  wb.sheets['PANEL'].api.ChartObjects():
                chart.Chart.Export(output_dir+'\\chart' + str(i) + ".png")
                i = i+1

            doc.replace_pic('Placeholder_1.png', 'chart0.png')
            doc.replace_pic('Placeholder_2.png', 'chart1.png')
            doc.replace_pic('Placeholder_3.png', 'chart2.png')
            doc.replace_pic('Placeholder_4.png', 'chart3.png')
            ## close excel     
            wb.close()

    doc.render(context)
    doc.save(output_name)

The script works fine however the only problem I have is that once the template document is taken, and filled with my predefined placeholders from the caller spreadsheet, the new document loses the 'link' to the spreadsheet. Therefore if I reword the new report, and also find that I need to redo some calculations in my original excel spreadsheet down the line, I am unable to update the figures in "Final_Report.docx" with new updated figures from the caller spreadsheet using the same macro. It would instead, if ran again, make a new "Final_Report.docx", losing any wording I made to the report I originally generated.

Is there anyway I can maintain a link between the caller spreadsheet, and the document I create from my template doc, for both my placeholder words, and the images I insert as PNGs, allowing me to re-update placeholders if calculations change?

Thanks for any support, very new to python so sorry if not worded too well!

0 Answers
Related