Automating MS Phrase Stories Creation and Sending

Stories are important half in lots of organizations needing to maintain beneath monitoring some elements that are core for the enterprise. Automating these stories normally require superior software program, however we will obtain the identical aim with python-docx and Raspberry PI

On this tutorial, I’m going to indicate you the way to set up python-docx on Raspberry PI laptop boards, additionally exhibiting the way to use it and the way to automate report creation and sending by e mail.

Python-docx is a library that permits the creation and manipulation of Microsoft Phrase (.docx) recordsdata from python. Easy, artificial, and precisely explaining what it goals to do. The benefit of utilizing python-docx is that you should use it inside a python script and create automated procedures to create or edit paperwork.

I'll use it in a script with Mutt, so enabling a quick and direct option to create and ship stories from a single python script. Furthermore, with cron, we will additionally automate this execution and schedule to execute at an outlined frequency.

For the next process, I’ve used a Raspberry PI 3 Mannequin A+ board. This process will work with any Raspberry PI laptop board (besides Raspberry PI Pico, which is a Microcontroller, not a pc)

What We Want

raspberry pi 3 model A+

As common, I recommend including from now to your favourite e-commerce purchasing cart all wanted {hardware}, in order that on the finish it is possible for you to to guage total prices and resolve if proceed with the undertaking or take away them from the purchasing cart. So, {hardware} can be solely:

Verify {hardware} costs with the next hyperlinks:

Amazon raspberry pi boards box
Amazon Raspberry PI 3 Model A+ box
Amazon Micro SD box
Amazon Raspberry PI Power Supply box

Step-by-Step Process

Put together OS

Begin putting in your Working System. I recommend putting in Raspberry PI OS Lite, so having a quick, headless OS. However you too can use Raspberry PI OS Desktop, on this case working from its inside terminal.

From the terminal, be certain your OS is up to date:

sudo apt replace -y && sudo apt improve -y

Now you'll be able to set up python-docx, simply after putting in pip3 and lxml (which is required). From the terminal, use the next 2 instructions:

sudo apt set up python3-pip python3-lxml
pip3 set up python-docx

At this level, you have already got all the things wanted to make use of python-docx. Within the following paragraph, I'll clarify the way to use the primary strategies.

Python-docs Principal Strategies/Properties

Making a New Doc

Every python script might want to begin by importing python-docx library:

from docx import Doc

With python-docx you'll be able to create a brand new doc by utilizing the next line:

doc = Doc()

With this line, we created a brand new empty doc, however we didn’t nonetheless reserve it. Please word that the Doc() class can even open current paperwork. That is notably helpful, for instance, once we wish to begin from a template as an alternative of writing an empty file. The code line can be:

doc = Doc('/path/to/TEMPLATE.docx')

Add a Heading

So as to add a heading you'll use the next line:

from docx import Doc
doc.add_heading('Doc Title', stage=0)

The “stage=0” is an elective parameter and signifies the title stage. Degree zero is the doc title and is the default when no stage is indicated:

python-docx tutorial 01

Different ranges could be added and leading to an entire title construction. Following code:

from docx import Doc
doc = Doc()
doc.add_heading('Doc Title')
doc.add_heading('Title 1', stage=1)
doc.add_heading('Title 2', stage=2)
doc.add_heading('Title 3', stage=3)
doc.add_heading('Title 4', stage=4)
doc.add_heading('Title 5', stage=5)
doc.add_heading('Title 6', stage=6)
python-docx tutorial 02

Add a Paragraph

Including a paragraph could be achieved with following line:

doc.add_paragraph("Hey from peppe8o!")

With the next end result:

python-docx tutorial 03

When you have to add particular formatting to your paragraph, you should use a variable so as to add the brand new textual content after which apply the brand new format as follows:

paragraph = doc.add_paragraph('This can be a bullet')
paragraph.type = 'Record Bullet'

having the next end result:

python-docx tutorial 04

That is additionally a helpful option to handle paragraphs with altering characters format. On this case, you'll use the “add_run” technique so as to add textual content to be threated with particular formattin (as an alternative of add_paragraph, which might go to a brand new line):

paragraph = doc.add_paragraph('Hey from ')
run = paragraph.add_run('peppe8o')
run.daring = True
paragraph.add_run(' weblog')
python-docx tutorial 05

Add a Desk

Including a desk is so simple as with a paragraph. You'll in all probability have to handle cells so as to insert single values, so utilizing a variable to determine the desk is all the time one of the simplest ways:

desk = doc.add_table(rows=3, cols=2)
python-docx tutorial 06

Observe: the desk is created with out borders. I set them so as to make the desk seen. However you'll have to set the border with desk.type = ‘Desk Grid’ after add.desk assertion

You could have 2 methods so as to add content material to your cells. The sooner one is by immediately calling the cell and utilizing textual content property:

desk.cell(0, 1).textual content='Regular Cell'

The second is by utilizing the paragraphs add_run technique, which permits us to use particular formatting contained in the cell after setting the textual content:

cell = desk.cell(0, 0)
run =cell.paragraphs[0].add_run('Bolded Cell')
run.daring = True

The next image exhibits the outcomes distinction:

python-docx tutorial 07

If you have to add a further row to an current desk, you will get it with:


Add a Image

Footage are one other widespread object for Phrase paperwork. The way in which python-docx integrates them in paperwork is all the time the identical:


Or, utilizing absolutely the path:


Copy an image in your script path or, should you don’t have, you will get the next from python-openxml GitHub examples:


On this approach, supposing that you're working from /residence/pi folder, each the instructions:




will return the identical output:

python-docx tutorial 08

Add a web page break

When you have to transfer into a brand new web page, you'll probably want the web page break aspect. With python-docx you'll be able to add this aspect with the next line:


Instance 1: the default Demo.docx

This “” can be out there from my obtain space:


If you wish to create it by your self, open a brand new file named “”:


Paste following code

from docx import Doc

doc = Doc()

doc.add_heading('Doc Title', 0)

p = doc.add_paragraph('A plain paragraph having some ')
p.add_run('daring').daring = True
p.add_run(' and a few ')
p.add_run('italic.').italic = True

doc.add_heading('Heading, stage 1', stage=1)
doc.add_paragraph('Intense quote', type='Intense Quote')

    'first merchandise in unordered record', type='Record Bullet'
    'first merchandise in ordered record', type='Record Quantity'

information = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')

desk = doc.add_table(rows=1, cols=3)
hdr_cells = desk.rows[0].cells
hdr_cells[0].textual content = 'Qty'
hdr_cells[1].textual content = 'Id'
hdr_cells[2].textual content = 'Desc'
for qty, id, desc in information:
    row_cells = desk.add_row().cells
    row_cells[0].textual content = str(qty)
    row_cells[1].textual content = id
    row_cells[2].textual content = desc


Save and shut.

Run the next command:


On the finish, you can see a brand new file, named “demo.docx”, with the next end result adopted by an empty web page (due to ultimate “add_page_break” earlier than the ultimate saving command from the script):

demo.docx file with python-docx

Instance 2: Customized Report from Raspberry PI System

With this in thoughts, we will create a customized report amassing data each from Raspberry PI or any exterior system reachable out of your RPI. On this approach, the report preparation could be totally automated.

An instance of this utilization is amassing Raspberry PI inside data like OS model, CPU temperature, networking standing and operating processes.

The total script is out there from my obtain space and you will get it immediately in your Raspberry PI with the command:


This script is constructed based mostly on what already defined in earlier paragraph, besides from the next perform:

def console(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    out, err =
    return out.decode('ascii').strip()

This half, utilizing subprocess library imported on the script starting, executes shell instructions from Python script, thus supplying you with again the shell end result.

In line with this situation, please bear in mind that you're operating te script as pi person. For this it is possible for you to to execute instructions out there to pi makes use of (“sudo” instructions require authentication, thus not giving again outcomes). For these instructions required priviledged permissions, methods are so as to add a permission to pi person for executing that command or executing python script from root (word that additionally set up steps must be carried out from root to make use of python-docx from root).

Anyway, my script runs with out the necessity of any further permission, so operating it:


will provide you with again a end result just like that extract:

python-docx tutorial custom Raspberry PI report

The total report is out there from following hyperlink: myReport.docx

Scheduling and Sending Stories by Electronic mail

Now, what misses is to make stories autmatically produced and despatched.

Set up Mutt to ship Electronic mail from Raspberry PI

Firstly, set up Mutt in your Raspberry PI. For this you'll be able to check with my Terminal Email Client with Raspberry PI and Mutt tutorial, which already covers all of the process.

Replace Script

We’ll add on the finish of our script the sending step by utilizing Mutt terminal command.

Append, after the “‘myReport.docx’)” row, the next line:

console('echo "Please discover final report hooked up" | mutt -s "Up to date report from Raspberry PI" -a "/residence/pi/myReport.docx"')

Please bear in mind to make use of your recipient e mail deal with.

Check your script with the terminal command:


This time, it's going to generate the report and in addition ship it to your recipient’s deal with. Verify your e mail (additionally spam folder, should you don’t discover it in your Inbox).

Schedule your Stories Technology and Sending

For this aim, we’ll use the built-in cron from Linux. From the terminal, open the cron for the pi person to edit with this command:

crontab -u pi -e

Choose your favourite textual content editor (1. Nano for me):

pi@raspberrypi:~ $ crontab -u pi -e
no crontab for root - utilizing an empty one

Choose an editor.  To vary later, run 'select-editor'.
  1. /bin/nano        <---- best
  2. /usr/bin/vim.tiny
  3. /bin/ed

Select 1-3 [1]: 1

Append the next line on the finish of the cron file, supposing that the script is in pi residence folder (or change accordingly to your folder path):

0 * * * * python3 /residence/pi/

It will execute the script (and ship the up to date report) each hour on the minute 0. You may customise frequency based on your wants. On the scheduled time, you'll obtain the report.

Get pleasure from!

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *