파이썬 워드 자동화

MS Word를 자동화하여 새 Word 문서(DOC 또는 DOCX)를 만들고 기존 문서를 편집 또는 수정하거나 Microsoft Office를 사용하지 않고 다른 형식으로 변환할 수 있습니다. Python MS Word 자동화를 사용하면 MS Word의 사용자 인터페이스를 통해 수행할 수 있는 모든 작업을 프로그래밍 방식으로 수행할 수 있습니다. 이 기사에서는 Python을 사용하여 Word 문서를 생성, 편집 또는 변환하기 위해 MS Word를 자동화하는 방법을 배웁니다.

이 기사에서는 Python을 사용하여 프로그래밍 방식으로 Word 문서를 생성하고 조작하는 데 필요한 모든 기본 기능을 다룹니다. 이 문서에는 다음 항목이 포함되어 있습니다.

Word 문서를 생성, 편집 또는 변환하는 Python MS Word 자동화 API

Word 자동화를 위해 Aspose.Words for Python API를 사용합니다. 프로그래밍 방식으로 Word 문서를 생성, 편집 또는 분석할 수 있는 완전하고 기능이 풍부한 Word 자동화 솔루션입니다. API의 Document 클래스는 Word 문서를 나타냅니다. API는 문서에 텍스트, 이미지 및 기타 콘텐츠를 삽입하는 다양한 메서드를 제공하는 DocumentBuilder 클래스를 제공합니다. 이 클래스는 또한 글꼴, 단락 및 섹션 서식 지정을 허용합니다. API의 Run 클래스는 글꼴 형식이 동일한 문자 실행을 나타냅니다. 다음 pip 명령을 사용하여 PyPI에서 Python 애플리케이션에 라이브러리를 설치하십시오.

pip install aspose-words

Python을 사용하여 Word 문서 만들기

다음 단계에 따라 프로그래밍 방식으로 Word 문서를 만들 수 있습니다.

  • 먼저 Document 클래스의 인스턴스를 만듭니다.
  • 다음으로 Document 객체를 인수로 사용하여 DocumentBuilder 클래스의 인스턴스를 만듭니다.
  • 그런 다음 DocumentBuilder 개체를 사용하여 일부 텍스트, 단락, 표 또는 이미지를 추가하는 요소를 삽입/작성합니다.
  • 마지막으로 출력 파일 경로를 인자로 하여 save() 메소드를 호출하여 생성된 파일을 저장합니다.

다음 코드 샘플은 Python을 사용하여 Word 문서(DOCX)를 만드는 방법을 보여줍니다.

import aspose.words as aw

# This code example demonstrates how to create a new Word document using Python.
# Create document object
doc = aw.Document()

# Create a document builder object
builder = aw.DocumentBuilder(doc)

# Specify font formatting Font
font = builder.font
font.size = 32
font.bold = True
font.name = "Arial"
font.underline = aw.Underline.SINGLE

# Insert text
builder.writeln("Welcome")
builder.writeln()

# Set paragraph formatting
font.size = 14
font.bold = False
font.name = "Arial"
font.underline = aw.Underline.NONE

paragraphFormat = builder.paragraph_format
paragraphFormat.first_line_indent = 8
paragraphFormat.alignment = aw.ParagraphAlignment.JUSTIFY
paragraphFormat.keep_together = True

# Insert paragraph
builder.writeln('''Aspose.Words for Python is a class library that enables your applications to perform a great range of document processing tasks. 
    It supports most of the popular document formats such as DOC, DOCX, RTF, HTML, Markdown, PDF, XPS, EPUB, and others. 
    With the API, you can generate, modify, convert, render, and print documents without third-party applications or Office Automation.
''')
builder.writeln()

# Insert a Table
font.bold = True
builder.writeln("This is a sample table")
font.bold = False

# Start table
table = builder.start_table()

# Insert cell
builder.insert_cell()
table.auto_fit(aw.tables.AutoFitBehavior.AUTO_FIT_TO_CONTENTS)

# Set formatting and add text
builder.cell_format.vertical_alignment = aw.tables.CellVerticalAlignment.CENTER

builder.write("Row 1 cell 1")
builder.insert_cell()
builder.write("Row 1 cell 2")
builder.end_row()

builder.insert_cell()
builder.write("Row 2 cell 1")
builder.insert_cell()
builder.write("Row 2 cell 2")
builder.end_row()

# End table
builder.end_table()
builder.writeln()

# Insert image
builder.insert_image("C:\\Files\\aspose-icon.png")

# Save document
doc.save("C:\\Files\\sample_output.docx")
Word 문서 만들기

Python을 사용하여 Word 문서를 만듭니다.

Python을 사용하여 Word 문서 편집 또는 수정

이전 섹션에서는 Word 문서를 만들었습니다. 이제 문서의 내용을 수정하고 변경해 보겠습니다. 다음 단계에 따라 Word 문서를 편집할 수 있습니다.

  • 먼저 Document 클래스를 사용하여 기존 Word 문서를 로드합니다.
  • 그런 다음 해당 인덱스로 특정 섹션에 액세스합니다.
  • 그런 다음 Run 클래스의 개체로 첫 번째 단락 콘텐츠에 액세스합니다.
  • 그런 다음 액세스한 단락에 대해 업데이트할 텍스트를 설정합니다.
  • 마지막으로 출력 파일 경로와 함께 save() 메서드를 호출하여 업데이트된 파일을 저장합니다.

다음 코드 샘플은 Python을 사용하여 Word 문서(DOCX)를 편집하는 방법을 보여줍니다.

import aspose.words as aw

# This code example demonstrates how to edit an existing Word document.
# Load the document
doc = aw.Document("C:\\Files\\sample_output.docx")

# Initialize document builder
builder = aw.DocumentBuilder(doc)

# Access the paragraph
paragraph = doc.sections[0].body.paragraphs[0].runs[0]
paragraph.text = "This is an updated text!"

# Save the document
doc.save("C:\\Files\\sample_updated.docx")
Word 문서 편집 또는 수정

Python을 사용하여 Word 문서를 편집하거나 수정합니다.

Python을 사용하여 Word 문서에서 텍스트 찾기 및 바꾸기

아래 단계에 따라 텍스트를 찾아 새 텍스트로 바꿀 수도 있습니다.

  • 먼저 Document 클래스를 사용하여 Word 문서를 로드합니다.
  • 다음으로 FindReplaceOptions 클래스의 인스턴스를 만듭니다.
  • 그런 다음 replace() 메서드를 호출합니다. 검색 문자열, 바꾸기 문자열 및 FindReplaceOptions 개체를 인수로 사용합니다.
  • 마지막으로 출력 파일 경로와 함께 save() 메서드를 호출하여 업데이트된 파일을 저장합니다.

다음 코드 샘플은 Python을 사용하여 Word 문서(DOCX)에서 특정 텍스트를 찾고 바꾸는 방법을 보여줍니다.

import aspose.words as aw

# This code example demonstrates how to find and replace text in Word document.
# Load the document
doc = aw.Document("C:\\Files\\sample_output.docx")

# Update using find and replace
# Specify the search string and replace string using the Replace method.
doc.range.replace("Aspose.Words", "Hello", 
    aw.replacing.FindReplaceOptions(aw.replacing.FindReplaceDirection.FORWARD))

# Save the document
doc.save("C:\\Files\\find_and_replace.docx")
Word 문서에서 텍스트 찾기 및 바꾸기

Word 문서에서 텍스트 찾기 및 바꾸기.

Python을 사용하여 Word 문서 변환

Word 문서를 PDF, XPS, EPUB, HTML, JPG, PNG 등과 같은 다른 형식으로 변환할 수 있습니다. Word 문서를 HTML 웹 페이지로 변환하려면 아래 단계를 따르십시오.

  • 먼저 Document 클래스를 사용하여 Word 문서를 로드합니다.
  • 다음으로 Document 개체를 인수로 사용하여 HtmlSaveOptions 클래스의 인스턴스를 만듭니다.
  • 그런 다음 cssstylesheettype, exportfontresources, resourcefolder 및 alias 속성을 지정합니다.
  • 마지막으로 출력 파일 경로와 HtmlSaveOptions 개체를 인수로 사용하여 save() 메서드를 호출하여 변환된 HTML 파일을 저장합니다.

다음 코드 샘플은 Python을 사용하여 Word 문서(DOCX)를 HTML로 변환하는 방법을 보여줍니다.

import aspose.words as aw

# This code example demonstrates how to convert a Word document to PDF.
# Load an existing Word document
doc = aw.Document("C:\\Files\\sample_output.docx")

# Specify save options
saveOptions = aw.saving.HtmlSaveOptions()
saveOptions.css_style_sheet_type = aw.saving.CssStyleSheetType.EXTERNAL
saveOptions.export_font_resources = True
saveOptions.resource_folder = "C:\\Files\\Resources"
saveOptions.resource_folder_alias = "C:/Files/resources"

# Save the converted document
doc.save("C:\\Files\\Converted.html", saveOptions)
Convert Word Documents using Python.

Convert Word Documents using Python.

마찬가지로 Word 문서를 지원되는 다른 형식으로 변환할 수도 있습니다. 문서에서 Word를 EPUB로, Word를 PDF로, Word 문서를 Markdown으로, Word를 JPG 또는 PNG 이미지로 변환하는 방법에 대해 자세히 읽어보십시오. .

Python을 사용하여 Word 문서 구문 분석

다음 단계에 따라 Word 문서를 구문 분석하고 내용을 일반 텍스트로 추출할 수 있습니다.

  • 먼저 Document 클래스를 사용하여 Word 문서를 로드합니다.
  • 다음으로 텍스트를 추출하고 인쇄합니다.
  • 마지막으로 save() 메서드를 호출하여 Word 문서를 텍스트 파일로 저장합니다. 이 메서드는 출력 파일의 경로를 인수로 사용합니다.

다음 코드 샘플은 Python을 사용하여 Word 문서(DOCX)를 구문 분석하는 방법을 보여줍니다.

import aspose.words as aw

# This code example demonstrates how to parse a Word document.
# Load the document
doc = aw.Document("C:\\Files\\Sample.docx")

# Extract text
print(doc.range.text)

# Save as plain text
doc.save("C:\\Files\\output.txt")

무료 라이선스 받기

임시 무료 라이선스 받기 평가 제한 없이 라이브러리를 사용해 볼 수 있습니다.

결론

이 문서에서는 다음 방법을 배웠습니다.

  • Python을 사용하여 MS Word를 자동화합니다.
  • 프로그래밍 방식으로 Word 문서를 만들고 편집합니다.
  • DOCX 파일을 구문 분석하거나 변환합니다.
  • Python을 사용하여 Word 문서에서 텍스트를 찾고 바꿉니다.

또한 문서를 사용하여 Aspose.Words for Python API에 대해 자세히 알아볼 수 있습니다. 모호한 부분이 있는 경우 포럼을 통해 언제든지 문의해 주십시오.

또한보십시오