IronWord로 DOCX 파일에서 텍스트 추출하기
IronWord의 ExtractText() 메서드를 사용하면 C#에서 DOCX 문서 전체나 특정 단락 또는 표의 셀에서 텍스트를 추출할 수 있습니다. 간단한 API로 문서 처리와 데이터 분석에 활용할 수 있습니다.
-
1IronWord를 NuGet Package Manager로 설치하십시오
-
2다음 코드 조각을 복사하여 실행하세요.
using IronWord; // Quick example: Extract all text from DOCX WordDocument doc = new WordDocument("sample.docx"); string allText = doc.ExtractText(); Console.WriteLine(allText);Imports IronWord ' Quick example: Extract all text from DOCX Dim doc As New WordDocument("sample.docx") Dim allText As String = doc.ExtractText() Console.WriteLine(allText)Imports IronWord ' Quick example: Extract all text from DOCX Dim doc As New WordDocument("sample.docx") Dim allText As String = doc.ExtractText() Console.WriteLine(allText) -
3실제 운영 환경에서 테스트할 수 있도록 배포하세요.
오늘 프로젝트에서 IronWord 사용을 시작해보세요 무료 체험
기본 작업 절차(5단계)
- IronWord C# 라이브러리를 설치합니다.
new WordDocument()를 사용하여 기존 Word 문서를 로드합니다.- 문서에서
ExtractText()를 호출하여 모든 텍스트를 추출합니다. Paragraphs컬렉션을 사용하여 특정 단락에서 텍스트를 추출합니다.- 추출된 텍스트 콘텐츠를 처리하거나 내보냅니다.
DOCX 문서에서 모든 텍스트를 추출하는 방법은 무엇인가요?
ExtractText() 메서드는 Word 문서 전체에서 텍스트를 추출합니다. 이 예제에서는 새 문서를 만든 뒤 텍스트를 추가하고, ExtractText()를 사용하여 텍스트를 추출한 다음 콘솔에 출력합니다. 이는 기본적인 텍스트 추출 절차입니다.
추출된 텍스트는 문서의 논리적인 읽기 순서를 유지합니다. 이 방법은 제목, 단락, 목록 및 기타 텍스트 요소를 순차적으로 처리하므로 콘텐츠 분석 및 검색 색인 생성 애플리케이션에 이상적입니다.
using System;
using IronWord;
// Instantiate a new DOCX file
WordDocument doc = new WordDocument();
// Add text
doc.AddText("Hello, World!");
// Print extracted text from the document to the console
Console.WriteLine(doc.ExtractText());using System;
using IronWord;
// Instantiate a new DOCX file
WordDocument doc = new WordDocument();
// Add text
doc.AddText("Hello, World!");
// Print extracted text from the document to the console
Console.WriteLine(doc.ExtractText());Imports System
Imports IronWord
' Instantiate a new DOCX file
Dim doc As New WordDocument()
' Add text
doc.AddText("Hello, World!")
' Print extracted text from the document to the console
Console.WriteLine(doc.ExtractText())Imports System
Imports IronWord
' Instantiate a new DOCX file
Dim doc As New WordDocument()
' Add text
doc.AddText("Hello, World!")
' Print extracted text from the document to the console
Console.WriteLine(doc.ExtractText())추출된 텍스트는 어떤 모습인가요?

콘솔에는 어떤 결과가 출력됩니까?

특정 단락에서 텍스트를 추출하려면 어떻게 해야 하나요?
문서 전체를 처리할 필요가 없으면 특정 단락에서 텍스트를 추출할 수 있습니다. Paragraphs 컬렉션을 통해 필요한 단락에 접근하여 처리합니다. 구조화된 문서나 특정 섹션을 따로 처리해야 할 때 유용합니다.
이 예에서는 첫 번째 및 마지막 단락에서 텍스트를 추출하여 조합한 후 .txt 파일에 결과를 저장합니다. 이 기술은 문서 요약 도구에서 도입부와 결론부를 추출할 때 일반적으로 사용됩니다. 기능을 잠금 해제하기 위해 라이선스 키를 사용하는 것과 유사하게, Paragraphs 컬렉션은 특정 문서 요소에 대한 접근을 제공합니다.
using System.IO;
using System.Linq;
using IronWord;
// Load an existing DOCX file
WordDocument doc = new WordDocument("document.docx");
// Extract text and assign variables
string firstParagraph = doc.Paragraphs[0].ExtractText();
string lastParagraph = doc.Paragraphs.Last().ExtractText();
// Combine the texts
string newText = firstParagraph + " " + lastParagraph;
// Export the combined text as a new .txt file
File.WriteAllText("output.txt", newText);using System.IO;
using System.Linq;
using IronWord;
// Load an existing DOCX file
WordDocument doc = new WordDocument("document.docx");
// Extract text and assign variables
string firstParagraph = doc.Paragraphs[0].ExtractText();
string lastParagraph = doc.Paragraphs.Last().ExtractText();
// Combine the texts
string newText = firstParagraph + " " + lastParagraph;
// Export the combined text as a new .txt file
File.WriteAllText("output.txt", newText);Imports System.IO
Imports System.Linq
Imports IronWord
' Load an existing DOCX file
Dim doc As New WordDocument("document.docx")
' Extract text and assign variables
Dim firstParagraph As String = doc.Paragraphs(0).ExtractText()
Dim lastParagraph As String = doc.Paragraphs.Last().ExtractText()
' Combine the texts
Dim newText As String = firstParagraph & " " & lastParagraph
' Export the combined text as a new .txt file
File.WriteAllText("output.txt", newText)Imports System.IO
Imports System.Linq
Imports IronWord
' Load an existing DOCX file
Dim doc As New WordDocument("document.docx")
' Extract text and assign variables
Dim firstParagraph As String = doc.Paragraphs(0).ExtractText()
Dim lastParagraph As String = doc.Paragraphs.Last().ExtractText()
' Combine the texts
Dim newText As String = firstParagraph & " " & lastParagraph
' Export the combined text as a new .txt file
File.WriteAllText("output.txt", newText)문서 분석 시 서식, 위치 또는 내용 패턴을 기준으로 주요 단락의 텍스트를 추출할 수 있습니다. 필요한 단락만 처리하면 시간을 줄이고 관련성이 높은 콘텐츠에 집중할 수 있습니다.
첫 번째 단락에서 어떤 내용이 추출되었습니까?

마지막 단락에서 어떤 내용이 추출되었습니까?

결합된 텍스트는 출력 파일에서 어떻게 나타나나요?

위 스크린샷은 첫 번째 단락과 마지막 단락에서 텍스트를 각각 추출하고, 두 결과를 합쳐 텍스트 파일로 저장한 모습을 보여줍니다. 추출 과정에서 텍스트는 유지되고 서식 정보는 제거되므로 일반 텍스트를 처리하는 데 적합합니다.
DOCX 파일의 표에서 데이터를 추출하는 방법은 무엇인가요?
표에는 처리하거나 분석할 구조화된 데이터가 들어 있는 경우가 많습니다. IronWord에서는 행과 셀을 통해 표 데이터에 접근할 수 있습니다. 이 예제에서는 API 통계 표가 포함된 문서를 불러와 3행 4열의 셀 값을 추출합니다.
표 데이터 추출은 데이터 마이그레이션, 보고서 생성, 자동 데이터 수집에 필수적입니다. 표의 인덱스는 0부터 시작하므로 첫 번째 표는 Tables[0], 첫 번째 행은 Rows[0]으로 접근합니다. 라이선스 체계와 마찬가지로 일관된 방식으로 원하는 요소에 접근할 수 있습니다.
using System;
using IronWord;
using IronWord.Models;
// Load the API statistics document
WordDocument apiStatsDoc = new WordDocument("api-statistics.docx");
// Extract text from the 1st table, 4th column and 3rd row
string extractedValue = ((TableCell)apiStatsDoc.Tables[0].Rows[2].Cells[3]).ExtractText();
// Print extracted value
Console.WriteLine($"Target success rate: {extractedValue}");using System;
using IronWord;
using IronWord.Models;
// Load the API statistics document
WordDocument apiStatsDoc = new WordDocument("api-statistics.docx");
// Extract text from the 1st table, 4th column and 3rd row
string extractedValue = ((TableCell)apiStatsDoc.Tables[0].Rows[2].Cells[3]).ExtractText();
// Print extracted value
Console.WriteLine($"Target success rate: {extractedValue}");Imports System
Imports IronWord
Imports IronWord.Models
' Load the API statistics document
Dim apiStatsDoc As New WordDocument("api-statistics.docx")
' Extract text from the 1st table, 4th column and 3rd row
Dim extractedValue As String = DirectCast(apiStatsDoc.Tables(0).Rows(2).Cells(3), TableCell).ExtractText()
' Print extracted value
Console.WriteLine($"Target success rate: {extractedValue}")Imports System
Imports IronWord
Imports IronWord.Models
' Load the API statistics document
Dim apiStatsDoc As New WordDocument("api-statistics.docx")
' Extract text from the 1st table, 4th column and 3rd row
Dim extractedValue As String = DirectCast(apiStatsDoc.Tables(0).Rows(2).Cells(3), TableCell).ExtractText()
' Print extracted value
Console.WriteLine($"Target success rate: {extractedValue}")이 코드는 Tables, Rows, Cells 컬렉션 속성으로 표의 셀에 접근하는 방법을 보여줍니다. Cells 컬렉션에서 반환되는 ITableCell 인터페이스 객체는 TableCell로 캐스팅해야 ExtractText 메서드를 호출할 수 있습니다. 예를 들어 ((TableCell)cell).ExtractText()로 호출하며, 이를 위해 using IronWord.Models; 선언을 추가해야 합니다.
원본 표는 어떤 모습입니까?

표의 셀에서 어떤 값이 추출됩니까?

고급 텍스트 추출 시나리오
복잡한 문서를 다룰 때는 여러 추출 기법을 결합해야 할 수도 있습니다. 다음은 여러 요소에서 텍스트를 추출하고 각각 다르게 처리하는 방법을 보여주는 예시입니다.
using IronWord;
using IronWord.Models;
using System.Text;
using System.Linq;
// Load a complex document
WordDocument complexDoc = new WordDocument("report.docx");
// Create a StringBuilder for efficient string concatenation
StringBuilder extractedContent = new StringBuilder();
// Extract and process headers (assuming they're in the first few paragraphs)
var headers = complexDoc.Paragraphs
.Take(3)
.Select(p => p.ExtractText())
.Where(text => !string.IsNullOrWhiteSpace(text));
foreach (var header in headers)
{
extractedContent.AppendLine($"HEADER: {header}");
}
// Extract table summaries
foreach (var table in complexDoc.Tables)
{
// Get first cell as table header/identifier
string tableIdentifier = ((TableCell)table.Rows[0].Cells[0]).ExtractText();
extractedContent.AppendLine($"\nTABLE: {tableIdentifier}");
// Extract key metrics (last row often contains totals)
if (table.Rows.Count > 1)
{
var lastRow = table.Rows.Last();
var totals = lastRow.Cells.Select(cell => ((TableCell)cell).ExtractText());
extractedContent.AppendLine($"Totals: {string.Join(", ", totals)}");
}
}
// Save the structured extraction
System.IO.File.WriteAllText("structured-extract.txt", extractedContent.ToString());using IronWord;
using IronWord.Models;
using System.Text;
using System.Linq;
// Load a complex document
WordDocument complexDoc = new WordDocument("report.docx");
// Create a StringBuilder for efficient string concatenation
StringBuilder extractedContent = new StringBuilder();
// Extract and process headers (assuming they're in the first few paragraphs)
var headers = complexDoc.Paragraphs
.Take(3)
.Select(p => p.ExtractText())
.Where(text => !string.IsNullOrWhiteSpace(text));
foreach (var header in headers)
{
extractedContent.AppendLine($"HEADER: {header}");
}
// Extract table summaries
foreach (var table in complexDoc.Tables)
{
// Get first cell as table header/identifier
string tableIdentifier = ((TableCell)table.Rows[0].Cells[0]).ExtractText();
extractedContent.AppendLine($"\nTABLE: {tableIdentifier}");
// Extract key metrics (last row often contains totals)
if (table.Rows.Count > 1)
{
var lastRow = table.Rows.Last();
var totals = lastRow.Cells.Select(cell => ((TableCell)cell).ExtractText());
extractedContent.AppendLine($"Totals: {string.Join(", ", totals)}");
}
}
// Save the structured extraction
System.IO.File.WriteAllText("structured-extract.txt", extractedContent.ToString());Imports IronWord
Imports IronWord.Models
Imports System.Text
Imports System.Linq
' Load a complex document
Dim complexDoc As New WordDocument("report.docx")
' Create a StringBuilder for efficient string concatenation
Dim extractedContent As New StringBuilder()
' Extract and process headers (assuming they're in the first few paragraphs)
Dim headers = complexDoc.Paragraphs _
.Take(3) _
.Select(Function(p) p.ExtractText()) _
.Where(Function(text) Not String.IsNullOrWhiteSpace(text))
For Each header In headers
extractedContent.AppendLine($"HEADER: {header}")
Next
' Extract table summaries
For Each table In complexDoc.Tables
' Get first cell as table header/identifier
Dim tableIdentifier As String = DirectCast(table.Rows(0).Cells(0), TableCell).ExtractText()
extractedContent.AppendLine(vbLf & $"TABLE: {tableIdentifier}")
' Extract key metrics (last row often contains totals)
If table.Rows.Count > 1 Then
Dim lastRow = table.Rows.Last()
Dim totals = lastRow.Cells.Select(Function(cell) DirectCast(cell, TableCell).ExtractText())
extractedContent.AppendLine($"Totals: {String.Join(", ", totals)}")
End If
Next
' Save the structured extraction
System.IO.File.WriteAllText("structured-extract.txt", extractedContent.ToString())Imports IronWord
Imports IronWord.Models
Imports System.Text
Imports System.Linq
' Load a complex document
Dim complexDoc As New WordDocument("report.docx")
' Create a StringBuilder for efficient string concatenation
Dim extractedContent As New StringBuilder()
' Extract and process headers (assuming they're in the first few paragraphs)
Dim headers = complexDoc.Paragraphs _
.Take(3) _
.Select(Function(p) p.ExtractText()) _
.Where(Function(text) Not String.IsNullOrWhiteSpace(text))
For Each header In headers
extractedContent.AppendLine($"HEADER: {header}")
Next
' Extract table summaries
For Each table In complexDoc.Tables
' Get first cell as table header/identifier
Dim tableIdentifier As String = DirectCast(table.Rows(0).Cells(0), TableCell).ExtractText()
extractedContent.AppendLine(vbLf & $"TABLE: {tableIdentifier}")
' Extract key metrics (last row often contains totals)
If table.Rows.Count > 1 Then
Dim lastRow = table.Rows.Last()
Dim totals = lastRow.Cells.Select(Function(cell) DirectCast(cell, TableCell).ExtractText())
extractedContent.AppendLine($"Totals: {String.Join(", ", totals)}")
End If
Next
' Save the structured extraction
System.IO.File.WriteAllText("structured-extract.txt", extractedContent.ToString())이 예제는 여러 문서 요소에서 추출한 데이터를 구조화하는 방법을 보여줍니다. 이 방식은 문서 요약이나 색인을 만들거나 후속 처리를 위한 데이터를 준비할 때 유용합니다. 업그레이드로 소프트웨어 기능을 확장하듯, 여러 추출 방법을 조합하면 문서 처리 기능을 확장할 수 있습니다.
텍스트 추출을 위한 모범 사례
실제 운영 환경에서 텍스트 추출 기능을 구현할 때는 다음과 같은 모범 사례를 고려하십시오.
- 오류 처리: 손상되었거나 예기치 않은 구조를 가진 문서를 처리하기 위해 추출 코드를 항상 try-catch 블록으로 감싸세요.
- 성능 최적화: 대용량 문서 또는 일괄 처리 시 문서 전체 내용보다는 필요한 부분만 추출하는 것을 고려하세요.
- 문자 인코딩: 특수 문자나 여러 언어가 포함된 문서의 경우, 추출된 텍스트를 저장할 때 문자 인코딩을 주의하세요.
- 메모리 관리: 여러 문서를 처리할 때는 메모리 누수를 방지하기 위해
WordDocument객체의 리소스를 적절히 해제하세요.
텍스트를 추출하면 문서의 논리적인 읽기 순서는 유지되지만 서식은 제거됩니다. 서식 정보를 보존해야 한다면 IronWord의 다른 기능을 사용하거나 메타데이터를 별도로 저장하는 방법을 고려하세요. 운영 환경에 배포할 때는 변경 로그에서 최신 기능과 개선 사항을 확인하세요.
요약
IronWord의 ExtractText() 메서드는 DOCX 파일에서 텍스트를 추출하는 데 강력하고 유연한 방법을 제공합니다. 문서 전체를 추출하든, 특정 단락을 추출하든, 표 데이터를 추출하든, API는 목표를 달성하기 위한 간편한 방법을 제공합니다. 올바른 오류 처리 및 최적화 전략과 이 기술을 결합하여 다양한 텍스트 추출 시나리오를 효율적으로 처리할 수 있는 신뢰할 수 있는 문서 처리 애플리케이션을 구축할 수 있습니다.
더 복잡한 문서 처리에 활용할 수 있는 추가 기능은 확장 기능과 관련 문서에서 확인하세요.
자주 묻는 질문
IronWord를 사용하여 DOCX 문서에서 모든 텍스트를 어떻게 추출합니까?
IronWord를 사용하면 ExtractText() 메서드를 통해 DOCX 문서에서 모든 텍스트를 추출할 수 있습니다. 이 메서드는 헤더, 단락, 목록 및 기타 요소를 순차적으로 처리하여 논리적인 읽기 순서를 유지하면서 문서 전체의 텍스트 콘텐츠를 가져옵니다. 이는 콘텐츠 분석 및 검색 인덱싱 애플리케이션에 유용합니다.
DOCX 파일의 특정 단락에서 텍스트를 추출할 수 있습니까?
네, IronWord를 사용하면 Paragraphs 컬렉션에 접근하여 특정 단락에서 텍스트를 추출할 수 있습니다. 이 방법은 구조화된 콘텐츠가 있는 문서 또는 특정 섹션을 독립적으로 처리해야 할 때 적합합니다.
IronWord는 DOCX 파일의 표 셀에서 텍스트 추출을 어떻게 처리합니까?
IronWord는 Tables, Rows 및 Cells 컬렉션을 탐색하여 표 셀에서 추출할 수 있게 합니다. 0부터 시작하는 인덱싱을 사용하여 특정 셀에 접근할 수 있어 구조화된 문서에서 효율적인 데이터 마이그레이션, 보고서 생성 또는 수집 워크플로우가 가능합니다.
IronWord의 고급 텍스트 추출 시나리오는 무엇입니까?
고급 시나리오에는 헤더, 표 요약 정보 추출 및 여러 요소에서 추출한 콘텐츠의 결합이 포함됩니다. 이 접근 방식은 문서 요약 또는 색인 생성을 위해 유용하며, ExtractText() 및 특정 문서 요소 메서드를 조합하여 사용합니다.
IronWord에서 텍스트 추출을 위한 모범 사례는 무엇입니까?
IronWord를 사용하여 텍스트 추출을 구현할 때는 try-catch 블록을 사용하여 오류를 처리하고, 필요한 콘텐츠를 대상으로 하여 성능을 최적화하며, 문자 인코딩을 관리하고, 메모리 누출을 방지하기 위해 적절한 메모리 관리를 보장해야 합니다.
IronWord는 추출 중에 텍스트 순서를 유지하는 데 어떻게 도움을 줍니까?
IronWord는 헤더, 단락 및 목록과 같은 텍스트 요소를 순차적으로 처리하여 논리적인 읽기 순서를 유지합니다. 이러한 추출 구조는 내용 분석 및 인덱싱이 필요한 애플리케이션에 특히 가치가 있습니다.
IronWord를 사용하여 추출한 텍스트를 파일로 내보내려면 어떻게 해야 합니까?
텍스트를 추출한 후에는 C# 파일 처리 메서드인 File.WriteAllText를 사용하여 텍스트를 파일에 저장할 수 있으며, 튜토리얼에서는 단락 추출과 함께 결합된 텍스트가 output.txt 파일에 저장되는 방법을 보여 줍니다.
소개 및 결론 섹션을 개별적으로 추출할 수 있습니까?
네, Paragraphs 컬렉션 내에서 이를 대상으로 하여 소개 및 결론과 같은 특정 단락을 추출할 수 있습니다. 이 방법은 주요 섹션의 명확한 추출이 필요한 문서 요약 도구에 효과적입니다.
추출한 텍스트를 저장할 때 고려해야 할 인코딩 사항은 무엇입니까?
IronWord 사용자는 특히 특수 문자 또는 여러 언어가 포함된 문서를 다룰 때 문자 인코딩을 인지해야 합니다. 추출한 텍스트를 저장할 때 올바른 인코딩을 보장하는 것은 텍스트의 무결성을 유지하는 데 중요합니다.
대용량 문서에 대해 IronWord의 텍스트 추출을 어떻게 최적화할 수 있습니까?
대용량 문서의 경우 전체 콘텐츠를 추출하는 대신 필요한 부분만 대상으로 하여 텍스트 추출을 최적화하십시오. 이렇게 하면 효율성이 보장되고 처리 시간이 단축되며 IronWord의 모든 기능을 활용할 수 있습니다.
아흐마드는 C#, Python 및 웹 기술에 탄탄한 기반을 갖춘 풀스택 개발자입니다. 그는 확장 가능한 소프트웨어 솔루션 구축에 깊은 관심을 가지고 있으며, 실제 응용 프로그램에서 디자인과 기능이 어떻게 조화를 이루는지 탐구하는 것을 즐깁니다.