Тёмный
No video :(

Word DOCX From Template | Python 

Python 360
Подписаться 6 тыс.
Просмотров 41 тыс.
50% 1

#Automation #Python #CSV #DOCX
Over a year ago I was asked to create 100+ almost identical word documents as "workplans" for my day job (They did not know I use Python to get things done). Writing multiple word documents and copy and pasting location, date, and contact details from a CSV was not what I had in mind.
Although I was a senior network engineer my boss seemed to think I would enjoy this highly repetitive task. I said it would take days, in the end it took about an hour to write the code and 5 seconds to generate 150 word documents (DOCX).
Automating the creation of these almost identical word documents was made possible with Python, docxtpl, and 1x word 'template' - (which was essentially a word doc with curly braces around the bits that are unique within the document).
👍 If you want a fast VPS server with Python installed check out :
🌏 webdock.io/en?maff=wdaff--170
◼️◼️◼️ (note when I say template it is still : "DOCX" not "DOTX") ◼️◼️◼️
------------------------------------------------------------------------------------------------------------
I never expected the original video to be so popular, so I have remade it, using Windows, with newer and hopefully clearer explanations, and a full csv source file.
If you like this tutorial, or if it has saved you hours of your life please let me know as automating repetitive tasks with Python is very pleasing. It's the ultimate 'revenge' when an employer expects you to sit there and do it manually!
► The code here is written in Windows as opposed to Ubuntu in my earlier version of this video seen here : • Python code to dynamic...
Seeing as I was rewriting it I thought I'd do it for M$ Windows.
► If you use Mac, or Linux, you'll need to edit the file path syntax to suit.
► If you don't have M$ Office then "Libre" or "Open" Office will work just the same.
Become a patron 👍
🌏 / drpi
-- chapter timings --
---------------------------------
0:00 Introduction
01:00 pip instal docxtpl
04:07 Starting code
07:31 The CSV values for the Jinja placeholders
12:26 split the row to get individual values
16:45 149 word documents in 5 seonnds
-----------------------------------------------------------------------------
=================================================
Buy Dr Pi a coffee (or Tea)
☕ www.buymeacoffee.com/DrPi ☕
Subscribe to the RU-vid Channel
=================================
🌏 / drpicode
Follow on Twitter - to get notified of new videos
=================================================
🌏 / rngweb
Thumbs up yeah? (cos Algos..)
docxtpl
docx
word docx
python
jinja2
docx from csv
#docx #tutorials #python

Опубликовано:

 

5 авг 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 71   
@ThomasMonk1
@ThomasMonk1 2 года назад
Thank you so much for your video. It was just what I was needing. It was easy to follow and implement. I would like make one suggestion. Your use of the term "template" is confusing in the context of the Word program. Word templates have a file extension of ".dotx" which did not work with this python package. Of course it worked flawlessly when I saved the Word document as ".docx". I saw online where someone had a python script that would convert ".dotx" to ".docx". Once again, loved your video and your humor.
@python360
@python360 2 года назад
Ah thank you! - I'll pin this comment in case it helps others. I don't know Microsoft Word that well to be honest, so apologies for using the word 'template' - I get totally what you mean. I hope the code saves you lots of time in the long run and once again, many thanks for the constructive comment!
@ThomasMonk1
@ThomasMonk1 2 года назад
@@python360 Thanks to you. I am using it now. I know it will save me time and help prevent some mistakes by automating the process.
@python360
@python360 2 года назад
Brilliant. There are some more advanced things you can do with Jinja syntax as well, which were beyond the scope of my video, but if you need to, or want to use it then "Jinja2"is the topic to read up on. 👍👍
@tiagohenriques3681
@tiagohenriques3681 2 года назад
yeahhhhhhhhh
@wesley_silva504
@wesley_silva504 2 года назад
You probably saved me months of work. Thanks a lot!
@python360
@python360 2 года назад
Thank you for using the video, glad it helped 👍👍
@sergioibarra453
@sergioibarra453 2 года назад
Muchas muchas gracias eres un master, tu tutorial es lo que estaba buscando, saludos desde México
@python360
@python360 2 года назад
¡Gracias jefe! Realmente aprecio su amable comentario, me complace que haya sido útil y gracias por ayudar con el algoritmo 👍👍
@diptejthakkar9065
@diptejthakkar9065 2 года назад
Excellent...! As a Begineer, I have this task and You make this Easy for me. Appreciated...
@python360
@python360 2 года назад
Great, very pleased I could save you some time 👍👍
@BoldonBigLad
@BoldonBigLad Год назад
Brilliant, just what I wanted
@greenjoyce3001
@greenjoyce3001 Год назад
Good stuff. 👍
@monkey_see_monkey_do
@monkey_see_monkey_do 3 года назад
Ahhhh...... I can't stop laughing.... First sketch... Then current working directory name)))) AHHHH!!!!! Docx automation is awesome! I couldn't ever imagine this can be done so easily!
@python360
@python360 3 года назад
That was a 100% accurate recreation of a business BS phone call! 😎🐒 Glad you liked it man! - Audacity even has a filter to make voices sound like phone calls. Docxtpl is based on Jinja2 so much like you would do with Flask. 👍
@monkey_see_monkey_do
@monkey_see_monkey_do 3 года назад
@@python360 That's incredible! I still can't believe it's possible!
@python360
@python360 3 года назад
Pi Software Solutions ! 😉
@monkey_see_monkey_do
@monkey_see_monkey_do 3 года назад
@@python360 Man, I just released new video, please have look, I'd bet you'll be surprised)
@ifoopedu
@ifoopedu Год назад
TY.
@teja2647
@teja2647 2 года назад
Great explanation.i have tried same code for s.no name and age.it is printing correct values in loop execution but while generating word document it is giving the only first row data in all documents.very glad if u help with the solution.(indexing is going correct) Code: for i in op[1:]: print(i) sno=i.split(",")[0] name=i.split(",")[1] age=i.split(",")[2] context={ 'sno':sno, 'name':name, 'age':age } #print(sno,name,age) doc.render(context) doc.save("%s.docx" %str(name)) print("Success!!!!") Result:Printing first row data in all docs
@python360
@python360 2 года назад
That does all look correct. If you want, email me you code and template file, I'll check it tomorrow 👍
@alyezo
@alyezo Год назад
Wonderful mate, this helped alot! But I can't seem to get around on duplicating the template (with different variables) into another page in the same document. Is there a work-around for that? Thanks!
@python360
@python360 Год назад
Ah, yes, just duplicate your template page 1 onto its page 2 and adjust any variables inside the Jinja braces to suit... { }
@MohAmuza
@MohAmuza 2 года назад
when dealing with csv files it's better to use csv module cause what if your data cells has some comma, so now spliting by comma will not be an effective way, also what there is some missing values the index will change, in those situations csv module is the best way to deal with. in you csv file you had normal strings and no missing values that's why it was normal to not use csv module.
@python360
@python360 2 года назад
Good point. Yes, import CSV would be more reliable. Thanks for pointing it out 👍
@robertgoldstein5819
@robertgoldstein5819 4 месяца назад
thanks for the video... if you want it to have a specific format do you just put the variable in that format like {{ variable }} has font courier, bold, size 14 while other items in whatever format you wish? also could you dynamically adjust a table like this too with a template variable...combining this concept and what you described in another video?
@python360
@python360 4 месяца назад
Thanks for the comment. Yes to your 1st question, andas for the table width, I don't know, I'll do some tests and maybe make a video if I can - maybe try this : stackoverflow.com/a/43053996/12670189
@robertgoldstein5819
@robertgoldstein5819 4 месяца назад
@@python360 thanks. I tried it out yesterday... it worked out just fine, but I did {{variable}} to avoid spacing issues. I also did it using pandas and used a ms excel file vs csv format file... that was good so I could have the input use drop down lists and such. Also I noticed the pdf conversion library needed office installed. As I do most of my development in wsl, I wasn't sure how to install it. I found another library that is convert2pdf. it required libreoffice installed, which seemed to be ok. it just had 2 snags 1) It is verbose about the conversion 2) my footer font size got adjusted. I emailed the developer to see if there is a workaround. if you know how to install ms office in a headless way in Linux, then I can go towards your referenced pdf conversion library instead.
@danielhughes9662
@danielhughes9662 3 года назад
Hey great video, I have been trying to figure out how to loop through an array which outputs to a tag in the template. For example, if my tag is {{Header1}} and the list items are [a,b,c], I would like each of these items to be displayed individually. The purpose of this is to allow me to input text into a document as follows: 1. a 1.1 a sub-header 2. b 2.1 b sub-header Any alternative options that allow me to create headers and subheaders dynamically with docxtpl, please let me know!
@python360
@python360 3 года назад
Hi Daniel, Thank you, Have a look at : github.com/elapouya/python-docx-template/blob/master/tests/subdoc.py This is from Eric who wrote docxtpl The example shows add_heading('Heading, level 1', level=1) I haven't experimented, but by altering this and adding some extra fields {{ }} in your template file you may be able to do what you need?
@user-bt5gt1fy3t
@user-bt5gt1fy3t 10 месяцев назад
hello, in one of my application if user order more then one product we have to create same structure of table for each product dynamically and stable structure, style provide user only , we just know filed/label are fix. so any one can guide how we can achieve.
@python360
@python360 10 месяцев назад
Hello, have watch of this : ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-0UvAXp9_6Jc.htmlsi=zAGux42nYEOrTAf9 You can use conditional logic to modify what appears in the template and make it dynamic.
@user-lc2dh6zx5p
@user-lc2dh6zx5p Год назад
how could you use jinja to generate python code? especially how would you deal with indentation
@python360
@python360 Год назад
Are you actuslly adding python code into a word doc?
@richardb5226
@richardb5226 2 года назад
Thank you for this video. How to attach different xlsx files in word document?
@python360
@python360 2 года назад
How do you mean? As hyperlinks,?
@richardb5226
@richardb5226 2 года назад
Not an hyperlinks. Need to insert objects (.xlsx file) with Excel icon.
@richardb5226
@richardb5226 2 года назад
How to use Excel template instead of word document
@fernandojavierleon5442
@fernandojavierleon5442 2 года назад
Hello, how can I put images from a URL, I can't do it, I would like a video about that. Thanks!
@python360
@python360 2 года назад
Can you not download them first, using requests? That might be better.
@nahuelalvez8042
@nahuelalvez8042 2 года назад
Excelent, but, when i use the for cycle the result of print is the last registry, not the others. what can I be missing? Sorry for my english, I write little in english, I'm argentinian. Thanks!
@python360
@python360 2 года назад
That sounds like an indentation error..check indentation and move the print line to right 👍
@nahuelalvez8042
@nahuelalvez8042 2 года назад
@@python360 Yesssssss!!!! That's all!!! Thankyou so much!!!
@python360
@python360 2 года назад
@@nahuelalvez8042 Glad I could help! Thanks for watching the video!
@victorsartor
@victorsartor 2 года назад
How can I make "doc.save" save files inside another folder in the same workspace? Is it possible?
@python360
@python360 2 года назад
Yes absolutely you can. If you're on windows you could need to create the path as a variable: eg : filepath = r'c:\abc\def\' and add it inside some curly braces at the start of the fstring something like this: doc.save("f{filepath}{workplan_number}_workplan.docx}") You might also want to import OS so you can use os.chdir to move directory. Hope that helps, if not I can do a short video in the next day or so
@victorsartor
@victorsartor 2 года назад
@@python360 Thank you! Thank you! Thank you! You have helped me in the way I do my work! I know a bit of Python for other applications and get confused when I get out of the routine. I hope you will be taken by the same happiness I feel at the moment soon, my friend!
@python360
@python360 2 года назад
I know the feeling too. It's easy to get out of the routine of writing code if you get side tracked. Muchas gracias for your kind comments. 👍👍👍
@joaofelipefranklinpereira561
Very good video, how would it be if I were to change a tag for example for an image? I tried like this but it corrupted the file hehe from docx import Document from docxtpl import DocxTemplate document = Document() p = document.add_paragraph() r = p.add_run() F001 = r.add_picture('images/foto1.jpg') doc = DocxTemplate("replacingTest.docx") context = {'FIBO_EM_2ANO_FGB_C1_GRA_CD_cap1_F001': F001} doc.render(context) doc.save('Preparado.docx')
@JSLEngineering
@JSLEngineering 2 года назад
Thank you for the clear explanation and demonstration. Is it also possible to get the variable name and variable value from a csv file and process it with the context line.? Workplan_number = i.split(",")[1] as X = Y X And ​​Y define from csv file by using the split function I tried but can't get it to work, probably you can help me with this.
@python360
@python360 2 года назад
Thank you! Yes, have you watched this one where I read values from a CSV? ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-0UvAXp9_6Jc.html If that doesn't help let me know 👍👍
@JSLEngineering
@JSLEngineering 2 года назад
Almost what I am looking for. I have an csv export from a database with 2 collumns. Column A = Variabelname Column B = Variable value In my template I have a few variablenames, but not al the variablename from the csv. My export is overcomplete and I want to use this export for different documents. So I like to control the values that I need for the documents in the templates and not in de export. My code: ----------------- from docxtpl import DocxTemplate with open("export.csv", "r", encoding='utf-8-sig') as csv_file: data_XXX = csv_file.readlines() doc = DocxTemplate("template.docx") content = {} for i in data_XXX: conontent = (f' { i.split(";")[0] + ":" + i.split(";")[1]}') doc.render(content) doc.save("Generate_document.docx") ---------------- error: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jinja2/environment.py", line 1286, in render ctx = self.new_context(dict(*args, **kwargs)) ValueError: dictionary update sequence element #0 has length 12; 2 is required
@python360
@python360 2 года назад
Content is a dictionary, you'll need to get the key:value pairs (so don't use list index) You can use for k,v in content.items(): return k,v
@JSLEngineering
@JSLEngineering 2 года назад
@@python360 thanks for your quick respons! its works right now.
@python360
@python360 2 года назад
Nice work! Glad I helped fix it 👍👍
@evanleesyoutoob
@evanleesyoutoob 11 месяцев назад
Hi, wondering what you can do if an entire section of the document is a “variable”?
@python360
@python360 11 месяцев назад
Maybe look to convert it to one big string in python first and then declare as a variable to pass to the template { my_long_string }
@evanleesyoutoob
@evanleesyoutoob 11 месяцев назад
@@python360 this is what I was thinking as well. Thanks for the advice, will give it a shot! My first time using Python or PySimpleGUI :)
@riwell4919
@riwell4919 3 года назад
It makes me this : Process finished with exit code 0 but I don't find any file
@python360
@python360 3 года назад
Ok. If you want to send your code I can take a look. k*n-worthington@protonmail.com (replace the * with an 'e')
@innocent8484
@innocent8484 Год назад
Thank you so much. I have a problem when ı want export to richtextfield . how do i solve the problem.
@python360
@python360 Год назад
how do you mean? - It exports to just 'docx'
@innocent8484
@innocent8484 Год назад
​@@python360 I'm sorry my English is not very good. I couldn't express it fully. One of the fields in my Django model is richtext field. When I export the data of this field to a word file. I cannot read the data of the part with the rich text field. This is my problem, thanks for your attention.
@python360
@python360 Год назад
@@innocent8484 Have a look at this: docxtpl.readthedocs.io/en/latest/#richtext-1 I've not tried it yet, but it should handle Rich text for you.
@aminamini9191
@aminamini9191 2 года назад
🌹🌹♥️♥️💜💜
@python360
@python360 2 года назад
Thanks Armin
@NacomSM
@NacomSM Год назад
What are the requeriments to install docxtpl?
@python360
@python360 Год назад
six python-docx docxcompose jinja2 lxml
@kevon217
@kevon217 Год назад
User\piss: nice…
@python360
@python360 Год назад
Pi Software Solutions
@it_russian1901
@it_russian1901 Год назад
GitHub please
Далее
The most important Python script I ever wrote
19:58
Просмотров 176 тыс.
I Built 3 SECRET Rooms In School!
33:34
Просмотров 13 млн
3 PYTHON AUTOMATION PROJECTS FOR BEGINNERS
17:00
Просмотров 1,6 млн
How to Replace VBA with Python(Step-By-Step Tutorial)
31:19
Créer des fichiers Word® avec Python®
13:46
Просмотров 1,1 тыс.
JPEG is Dying - And that's a bad thing
8:09
Просмотров 17 тыс.