[Python] 문서 자동화 (docx-template)

2023. 9. 13. 15:00·Python
반응형

[Python] 문서 자동화 (docx-template)에 대해 학습 후 정리한 포스팅 입니다.

 

 

 

이번 포스팅에서는 [Python] 문서 자동화 (docx-template)에 대해 학습합니다.

 

 

I) docx-template 이란?

docx-template는 Python에서 사용할 수 있는 라이브러리로, Word 문서의 템플릿을 쉽게 채울 수 있게 해줍니다.

즉, 문서 자동화를 위한 라이브러리입니다. 아래 링크에서 자세한 document를 확인할 수 있습니다.

 

Welcome to python-docx-template’s documentation! — python-docx-template 0.9.x documentation

RichText When you use {{ }} tag in your template, it will be replaced by the string contained within var variable. BUT it will keep the current style. If you want to add dynamically changeable style, you have to use both : the {{r }} tag AND a RichText obj

docxtpl.readthedocs.io

 

 

II) docx-template 설치

pip install docxtpl

conda install docxtpl --channel conda-forge

위 명령어들을 통해 pip, conda 환경에서 설치할 수 있습니다.

 

 

III) docx-template 기본 사용법

1) 변수 넣기
{{ company_name }}이 있는 my_word_template.docx를 준비합니다.

from docxtpl import DocxTemplate

doc = DocxTemplate("my_word_template.docx")
context = {'company_name': "World company"}
doc.render(context)
doc.save("generated_doc.docx")

코드를 실행하면 {{ company_name }} 위치에 World company가 삽입되어 generated_doc.docx로 생성됩니다.


2) 템플릿 태그

  • 변수 치환: {{ variable_name }}
  • 조건문, 반복문 등의 Jinja2 태그: {% if ... %}, {% for ... %}
  • 문단, 테이블 행, 테이블 열, 런(글자 스타일 그룹)을 관리하기 위한 특별한 태그:
    • {%p jinja2_tag %}: 문단
    • {%tr jinja2_tag %}: 테이블 행
    • {%tc jinja2_tag %}: 테이블 열
    • {%r jinja2_tag %}: 런

3) RichText

 스타일을 동적으로 변경할 수 있는 텍스트 객체입니다.

from docxtpl import RichText
rt = RichText('Some text')

 

4) 이미지 삽입

from docxtpl import InlineImage
myimage = InlineImage(tpl, 'path_to_image.png', width=Mm(20))

 

 

5) 서브 문서

sd = tpl.new_subdoc('path_to_subdoc.docx')

 

 

IV) 포트폴리오 자동화 실습

자신의 포트폴리오를 자동으로 작성해주는 프로그램을 만들어봅시다.

 

1) portfolio_template.docx 생성

그전에 일단 반복될 수 있는 요소를 변수로 처리하여 portfolio_template.docx를 만들겠습니다.

변수안의 내용이 채워져 portfolio_result.docx의 문서로 저장되는 코드를 작성하겠습니다.

프로젝트의 개수에 따라 프로젝트 테이블의 행이 결정됩니다.

 

2) 코드 생성

from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm

tpl = DocxTemplate('portfolio_template.docx')
myimage = InlineImage(tpl, image_descriptor='cat.jpg', width=Mm(40), height=Mm(40))
context = {
    'name' : '홍길동',
    'introduce' : '안녕하세요. 저는 홍길동입니다.',
    'image' : myimage,
    'project_1': '프로젝트1: AI 프로젝트',
    'project_2': '프로젝트2: 앱 개발',
    'experience': '코딩 교육 봉사',
    'career': 'ㅇㅇ회사 2023-03-02~2023-09-05',
    'education': 'ㅇㅇ대학교 2023-03-02~2023-09-05',
    'certification': '정보처리기사',
    'awards': '교내 SW 경진대회 1등',
    'col_labels': ['역할', '기간', '느낀점', '기술'],
    'tbl_contents': [
        {'label': 'AI 프로젝트', 'cols': ['AI 모델링', '2023-09-01~09-05', '개발자의 기본 역량', 'Tensorflow']},
        {'label': '앱 개발', 'cols': ['백엔드 API 개발', '2023-08-01~09-05', '협업의 중요성', 'Node.js']},
        {'label': '웹 페이지 개발', 'cols': ['프론트엔드 개발', '2023-06-01~08-05', '유지보수의 중요성', 'react']},
    ],
}

tpl.render(context)
tpl.save('portfolio_result.docx')

 

 

3) 결과물 확인 (portfolio_result.docx)

자동으로 포트폴리오가 예쁘게 생성된 것을 확인할 수 있습니다.

보고서 템플릿, 코드, 결과를 첨부하며 이번 포스팅 마무리 하겠습니다.

portfolio_result.docx
0.05MB
portfolio_template.docx
0.02MB
test.py
0.00MB

 

 

 

<Summary>

- [Python] 문서 자동화 (docx-template)

- docx-template 이란?

- docx-template 설치

- docx-template 기본 사용법

- 포트폴리오 자동화 실습

 

 

 

 

*유의사항

- AI 산업기능요원이 공부하여 남긴 정리입니다.

 

반응형
저작자표시 (새창열림)

'Python' 카테고리의 다른 글

[Python] 문자열 내 문자 및 인덱스 찾기 (count(), find(), index())  (3) 2023.09.15
[Numpy] squeeze & unsqueeze - 배열의 모양 변경  (0) 2023.08.19
[Python] 리스트 컴프리헨션(List Comprehension)  (0) 2023.08.18
[screen] Linux 터미널 다중화 도구  (0) 2023.08.17
[tqdm] 진행 상황 표시 모듈  (0) 2023.08.16
'Python' 카테고리의 다른 글
  • [Python] 문자열 내 문자 및 인덱스 찾기 (count(), find(), index())
  • [Numpy] squeeze & unsqueeze - 배열의 모양 변경
  • [Python] 리스트 컴프리헨션(List Comprehension)
  • [screen] Linux 터미널 다중화 도구
성 언
성 언
AI 학과 3학년 학생이자 RAG 기반 LLM 챗봇 개발 회사에서 근무 중입니다. AI 챗봇 개발과 관련된 기술, 연구, 그리고 실험 과정에서 얻은 인사이트를 공유합니다. 최신 AI 기술을 함께 탐구하며 성장해 나가요!
    반응형
  • 성 언
    AI EON
    성 언
  • 전체
    오늘
    어제
    • AII
      • NLP
      • AI Paper Review
      • MLOps
      • Python
      • Algorithm
      • Memo
      • Server Developer
        • Node.js
        • DataBase&Data Engineering
        • Server Basic
      • MATH
        • Linear Algebra
        • AI
      • etc
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    배타 잠금
    패스트캠퍼스 수강 후기
    파이썬
    Signature 초격차 패키지
    파이썬 문서 자동화
    리랭커
    팬텀 읽기
    문서 자동화
    다중 버전 동시성 제어
    NVML
    비반복 읽기
    그리디 알고리즘
    node.js
    더티 쓰기
    Ubuntu-20.04 APM 소스 설치
    배열의 모양 변경
    umc
    word 자동화
    reranker
    백준
    스택
    map 함수
    docx-template
    Python
    c++
    더티 읽기
    알고리즘
    [Numpy] squeeze & unsqueeze
    transaction
    트랜잭션
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
성 언
[Python] 문서 자동화 (docx-template)
상단으로

티스토리툴바