How to use python MS OFFICE templates similar to Jinja2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
from __future__ import print_function import os import time import pandas as pd from mailmerge import MailMerge class Loader(object): def __init__(self, templates_dir, outputs_dir, xlsx_file, sheet_name, doc_template): """ :param templates_dir: :param outputs_dir: :param xlsx_file: :param sheet_name: :param doc_template: """ self.templates_dir = os.path.join(os.getcwd(), templates_dir) self.outputs_dir = os.path.join(os.getcwd(), outputs_dir) self.xlsx_file = xlsx_file self.sheet_name = sheet_name self.doc_template = os.path.join(self.templates_dir, doc_template) self.python_to_docx_instance = MailMerge(self.doc_template) def load_products_from_file(self, _file_name=None, _sheet_name=None): """ :param _file_name: :param _sheet_name: :return: """ _file_name = _file_name or self.xlsx_filename _sheet_name = _sheet_name or self.sheet_name xl = pd.ExcelFile(_file_name) _data_frame = xl.parse(_sheet_name) return _data_frame def data_frame_from_excel(self): """ :return: """ _origin = self.load_products_from_file(self.xlsx_file, self.sheet_name) _origin['VALUE'] = _origin['VALUE'].map(lambda x: str(x)) _origin['PROPERTY'] = _origin['PROPERTY'].map(lambda x: x.strip()) _origin = _origin.set_index("PROPERTY") return _origin def output_name(self, desired_name): """ :param desired_name: :return: """ name = os.path.join(self.outputs_dir, time.strftime("%Y.%m.%d.%H.%M.%S") + desired_name + '.docx') return name def dict_from_keys(self, my_dict): """ :param my_dict: :return: """ return dict.fromkeys(my_dict, 0) def process_document(self, name): """ :param name: :return: """ instance_dict = self.dict_from_keys(self.python_to_docx_instance.get_merge_fields()) origin = self.data_frame_from_excel() filled_instance_dict = {k: origin.loc[k]['VALUE'] for k, v in instance_dict.items()} self.python_to_docx_instance.merge(**filled_instance_dict) self.python_to_docx_instance.write(self.output_name(name)) ''' * ********************************** * LOADED TEMPLATES FOR * - pracovna zdravotna sluzba * - BOZP * - poziarna orchana * * *********************************** ''' tpl = 'templates' out = 'outputs' file_name = "loader.xlsx" sheet_name = "data" pzs_document = 'pracovna_zdravotna_sluzba.docx' po_document = 'poziarna_ochrana.docx' bozp_document = 'bozp.docx' ''' Create desired documents :) ''' pzs = Loader(tpl, out, file_name, sheet_name, pzs_document) pzs.process_document('_pzs') po = Loader(tpl, out, file_name, sheet_name, po_document) po.process_document('_po') bopz = Loader(tpl, out, file_name, sheet_name, bozp_document) po.process_document('_bozp') |