Skip to content

Instantly share code, notes, and snippets.

@rdapaz
Last active May 22, 2020 07:06
Show Gist options
  • Save rdapaz/63825177bdcd29f2443274dbd5cfb369 to your computer and use it in GitHub Desktop.
Save rdapaz/63825177bdcd29f2443274dbd5cfb369 to your computer and use it in GitHub Desktop.
Generate document from data
# coding: utf-8
import os
import sys
import pprint
import win32com.client
import yaml
def pretty_printer(o):
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(o)
class Word:
def __init__(self):
self.app = win32com.client.gencache.EnsureDispatch("Word.Application")
self.app.Visible = True
self.app.DisplayAlerts = False
self.doc = self.app.Documents.Add()
self.rge = self.doc.Range(Start=0, End=0)
def initialise(self):
self.rge.InsertAfter("\n\n")
self.rge.Select()
def gotoEndofRange(self):
self.rge = self.doc.Range(Start=0, End=0)
self.rge.Expand(Unit=6)
# self.rge.Collapse(0)
self.rge.InsertAfter("\n\n")
def insertTable(self, autoTextName = 'sec'):
self.app.Selection.TypeText(Text=autoTextName)
try:
self.app.Selection.Range.InsertAutoText()
except:
print(self.app.Selection.Range.Text)
rge = self.doc.Range()
def updateTable(self, tbl_id, data):
heading_rows = 1
table = self.doc.Tables(tbl_id)
rows_count = table.Rows.Count
if not rows_count >= len(data) + heading_rows:
table.Select()
self.app.Selection.InsertRowsBelow(NumRows=len(data) + heading_rows - rows_count)
i = heading_rows
for entry in [[row[0], row[2]] for row in data ]:
i += 1
for n in range(len(entry)):
table.Cell(i, n+1).Range.Text = entry[n]
def generateEvidence(self, tbl_id, data):
self.insertTable(autoTextName='sec')
self.updateTable(tbl_id, data)
if __name__ == '__main__':
word = Word()
new_data = []
with open(r'workworkworkworkwork.yaml', 'r') as fin:
data = yaml.load(fin)
# pretty_printer(data)
for entries in data:
for device, step_data in entries.items():
for idx, s in enumerate(step_data, 1):
desc = "".join([s['Desc'], '\n', s['Code'] if 'Code' in s else ''])
new_data.append([idx, device, desc])
devices = sorted(list(set([x[1] for x in new_data])))
print(devices)
tbl_id = 0
count = 0
for device in devices:
print(f'[+] Executing device: {device}...')
count += 1
tbl_id += 1
device_data = [p for p in new_data if p[1] == device]
word.generateEvidence(tbl_id, device_data)
word.gotoEndofRange()
# if count == 1:
# break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment