python(14) docx 문서 만들기

hyukstory 혁스토리·2020년 8월 26일
0

python

목록 보기
20/35

pip install python-docx

1. 워드 문서 불러오기

import docx

doc = docx.Document("C:/Users/student/Desktop/python/P_3week/Test.docx")

len(doc.paragraphs)
type(doc.paragraphs)

for i in doc.paragraphs :
    print(i.text)

2. 워드 문서 저장

doc = docx.Document()
doc.add_paragraph('HELLO WORLD!')
doc.save('C:/Users/student/Desktop/python/P_3week/hello.docx')

3. 내용 추가

import docx
doc = docx.Document()
doc.add_paragraph('Hello World')
paraobj1 = doc.add_paragraph('This is a second paragraph.') # 단락 추가
paraobj2 = doc.add_paragraph('This is a third paragraph.')  # 그냥 이어 붙이기
paraobj1.add_run('This is a second paragraph 에 추가')
doc.save('C:/Users/student/Desktop/python/P_3week/multi.docx')

4. 제목 추가

import docx
doc = docx.Document()
doc.add_heading('Header 0', 0)
doc.add_heading('Header 1', 1)
doc.add_heading('Header 2', 2)
doc.add_heading('Header 3', 3)
doc.add_heading('Header 4', 4)
doc.save('C:/Users/student/Desktop/python/P_3week/multi.docx')

doc.paragraphs[0].text

5. 페이지 나누기

import docx
doc = docx.Document()
doc.add_paragraph('첫 페이지 No.1')
doc.paragraphs[8].runs[0].add_break(docx.text.run.WD_BREAK.PAGE) # 강제로 새페이지 만들기 (runs[0] 은 고정)
doc.add_paragraph('두번째 페이지 No.2')
doc.save('C:/Users/student/Desktop/python/P_3week/multi.docx')

6. 그림 추가

import docx
doc = docx.Document()
doc.add_paragraph('세번째 페이지 No.3')
doc.add_picture("C:/Users/student/Desktop/python/P_3week/cat.png", \
                width = docx.shared.Cm(10), \
                height = docx.shared.Cm(10))
doc.add_picture("C:/Users/student/Desktop/python/P_3week/cat2.jpeg", \
                width = docx.shared.Cm(10), \
                height = docx.shared.Cm(10))
doc.add_paragraph('네번째 페이지 No.4')
doc.save('C:/Users/student/Desktop/python/P_3week/multi.docx')
profile
문돌이의 고군분투 개발 공부

0개의 댓글