📜 ⬆️ ⬇️

Fill documents in Microsoft Word using Python. Part 2

We multiply the documents

.
In the previous post it was considered how to fill the request in word using python. This time it will be shown how to fill in several word documents with data from the excel table.

Before working with the program, we need to prepare an excel file, which will contain the original data. Create an excel file with such data or use ready-made:

image
')
Now turn to the program.

Since we have to read the excel file, we need to import the corresponding module:

import openpyxl 

Next, we need to go through the table and read all the data line by line. It will look like this:

 test=[] wb = openpyxl.load_workbook('zaprosi.xlsx') sheet=wb.get_active_sheet() for row in sheet['B3':'F7']: for cellObj in row: if cellObj.value==None or cellObj.value==" ": continue #print(cellObj.value) test.append(cellObj.value) 

We have created an empty list where we further add values ​​from the table. Adding occurs only if there are any records in the cell (not empty).

After the done manipulations, we will enter the collected data into the word template:

 doc = DocxTemplate(".docx") context = { 'emitent' : test[0],'address1' : test[1],'' : test[2],'_' : test[3],'director' : test[4] } doc.render(context) doc.save('-final.docx') 

As a result, we will have a ready-made word file with data from the table. Only here it is one, and is called the final template. How then to distinguish the documents from each other?

Let's start with the simple. To save files each time under different names, you need to change at the end of the code to the following:

 doc.save(test[x]+'.docx') 

Now the saved file will have the name of the company sending the request.

During program execution, an error may occur:

image

This error is due to the fact that the company name contains quotes. If you remove the quotes from the excel table, the word file is successfully saved with the name Company-1.docx.

It remains to “propagate” the document by entering the remaining data from the table.

Here, too, everything is simple. We create a cycle based on our collected data:

 x=0 while x<len(test): doc = DocxTemplate(".docx") context = { 'emitent' : test[x],'address1' : test[x+1],'' : test[x+2],'_' : test[x+3],'director' : test[x+4] } doc.render(context) doc.save(test[x]+'.docx') x+=5 

At the end of the cycle, we “jump over” the name of the column with the name of the company so that the word file is preserved with the correct name.

The program is ready! It remains only to create an excel spreadsheet with companies that are serviced.

Download the finished program - here .

Download the excel spreadsheet with test data - here .

The word document template is here .

Source: https://habr.com/ru/post/459152/


All Articles