nrc-cnrc/MetroloPy

Metrolopy2word

vysiker opened this issue · 1 comments

Here is a suggestion for a Microsoft Word export of budget and frequency distribution. Might be interesting for people who don't know Latex.

Result
image

SourceCode

from docx import Document
import matplotlib
from docx.enum.section import WD_ORIENT, WD_SECTION
from docx.shared import Mm
def budget2word(budget,file,output=None):    
    df = budget.df_str
    doc = Document()
    section = doc.sections[-1]
    section.page_height = Mm(297)
    section.page_width = Mm(210)
    section.left_margin = Mm(25.4)
    section.right_margin = Mm(25.4)
    section.top_margin = Mm(25.4)
    section.bottom_margin = Mm(25.4)
    section.header_distance = Mm(12.7)
    section.footer_distance = Mm(12.7)
    t = doc.add_table(df.shape[0]+1, df.shape[1])
    t.style = doc.styles['Colorful List Accent 2']
    for j in range(df.shape[-1]):
        t.cell(0,j).text = df.columns[j]
    for i in range(df.shape[0]):
        for j in range(df.shape[-1]):
            t.cell(i+1,j).text = df.values[i,j] 
    if output is not None:
        matplotlib.pyplot.clf()
        uc.gummy.simulate([output],n=5e5)
        output.hist(p=0.95, density=False)
        matplotlib.pyplot.gca().set_ylabel("frequency distribution")
        output.k = 1
        matplotlib.pyplot.savefig(file.split(".")[0]+".png")
        doc.add_picture(file.split(".")[0]+".png")
    doc.save(file)

Execution

fname = 'budgets/budget.docx'
budget2word(budget,fname,output=outputVariable)

This is pretty nice. I could probably add docx as an optional dependency and implement this. Thanks!