가장 일반적이고 널리 사용되는 워드 프로세싱 파일 형식은 DOC, DOCXODT입니다. 유명한 Microsoft Word 및 OpenOffice Writer는 이러한 형식을 지원하며 일반적으로 문서 초안 작성에 이러한 형식을 사용합니다. 따라서 개발자는 프로그래밍 방식으로 응용 프로그램에서 Word 문서를 편집해야 합니다. 이 기사에서는 문서 편집을 위해 .NET API를 사용하여 C#에서 Word 문서를 편집하는 방법에 대해 설명합니다.

다음은 이 기사에서 간략하게 논의된 주제입니다.

Word 문서 편집 및 자동화를 위한 .NET API

이 기사에서는 문서 편집 API이며 개발자가 WYSIWYG HTML 편집기를 사용하여 다양한 문서 형식을 로드, 편집 및 저장할 수 있는 C# 예제에서 GroupDocs.Editor for .NET를 사용할 것입니다. 워드 프로세서 문서 형식 외에도 API는 스프레드시트, 프레젠테이션, HTML, XML, TXT, DSV, TSV 및 CSV 형식 편집을 지원합니다.

다운로드 섹션에서 DLL 또는 MSI 설치 프로그램을 다운로드하거나 NuGet을 통해 .NET 애플리케이션에 API를 설치합니다.

PM> Install-Package GroupDocs.Editor

C#에서 Word 문서 편집

API를 설정한 직후에 Word 문서 편집으로 빠르게 이동할 수 있습니다. 다음 단계를 통해 워드 프로세서 문서를 편집할 수 있습니다.

  • 워드 문서를 로드합니다.
  • 옵션으로 적절하게 편집하십시오.
  • 편집된 문서를 저장합니다.

Word 문서 로드

먼저 문서가 보호되어 있는 경우 문서 경로와 암호를 제공하여 문서를 로드합니다.

using (FileStream fs = File.OpenRead(inputFilePath))
{
    Options.WordProcessingLoadOptions loadOptions = new WordProcessingLoadOptions();
    loadOptions.Password = "password-if-any";
}

Word 문서 편집

로드한 후 요구 사항에 따라 로드된 문서를 편집할 수 있습니다. 여기서는 아래 C# 코드를 사용하여 Word 문서에서 “document"라는 단어의 모든 항목을 “edited document"로 바꿉니다.

    using (Editor editor = new Editor(delegate { return fs; }, delegate { return loadOptions; }))
    {
        Options.WordProcessingEditOptions editOptions = new WordProcessingEditOptions();
        editOptions.FontExtraction = FontExtractionOptions.ExtractEmbeddedWithoutSystem;
        editOptions.EnableLanguageInformation = true;
        editOptions.EnablePagination = true;
        using (EditableDocument beforeEdit = editor.Edit(editOptions))
        {
            string originalContent = beforeEdit.GetContent();
            List<IHtmlResource> allResources = beforeEdit.AllResources;
            string editedContent = originalContent.Replace("document", "edited document");
        }
    }

편집된 Word 문서를 옵션으로 저장

마지막으로 편집된 문서 내용을 저장하면서 다양한 옵션을 추가로 설정할 수 있습니다. 이러한 옵션에는 다음이 포함됩니다. 페이지 매김, 암호, 로케일, 보호 또는 메모리 최적화 설정을 설정합니다. 아래 코드에서 위의 옵션을 설정하고 편집된 문서를 암호로 보호된 읽기 전용 DOCX 파일로 저장합니다.

using (EditableDocument afterEdit = EditableDocument.FromMarkup(editedContent, allResources))
{
    Options.WordProcessingSaveOptions saveOptions = new WordProcessingSaveOptions(WordProcessingFormats.Docx);
    saveOptions.EnablePagination = true;
    saveOptions.Locale = System.Globalization.CultureInfo.GetCultureInfo("en-US");
    saveOptions.OptimizeMemoryUsage = true;
    saveOptions.Password = "password";
    saveOptions.Protection = new WordProcessingProtection(WordProcessingProtectionType.ReadOnly, "write\_password");
    using (FileStream outputStream = File.Create("filepath/editedDocument.docx"))
    {
        editor.Save(afterEdit, outputStream, saveOptions);
    }
}

완전한 코드

편의를 위해 위에서 설명한 전체 C# 예제를 보여 드리며 Word 문서를 편집한 다음 DOCX 형식으로 저장합니다.

// GroupDocs 문서 편집 및 자동화 API를 사용하여 C#에서 Word 문서 편집
using (FileStream fs = File.OpenRead("filepath/document.docx"))
{   // Load Document
    Options.WordProcessingLoadOptions loadOptions = new WordProcessingLoadOptions();
    loadOptions.Password = "password-if-any";
    // 문서 편집
    using (Editor editor = new Editor(delegate { return fs; }, delegate { return loadOptions; }))
    {
        Options.WordProcessingEditOptions editOptions = new WordProcessingEditOptions();
        editOptions.FontExtraction = FontExtractionOptions.ExtractEmbeddedWithoutSystem;
        editOptions.EnableLanguageInformation = true;
        editOptions.EnablePagination = true;

        using (EditableDocument beforeEdit = editor.Edit(editOptions))
        {
            string originalContent = beforeEdit.GetContent();
            List<IHtmlResource> allResources = beforeEdit.AllResources;

            string editedContent = originalContent.Replace("document", "edited document");
            // 문서 저장
            using (EditableDocument afterEdit = EditableDocument.FromMarkup(editedContent, allResources))
            {
                WordProcessingFormats docxFormat = WordProcessingFormats.Docx;
                Options.WordProcessingSaveOptions saveOptions = new WordProcessingSaveOptions(docxFormat);
                            
                saveOptions.EnablePagination = true;
                saveOptions.Locale = System.Globalization.CultureInfo.GetCultureInfo("en-US");
                saveOptions.OptimizeMemoryUsage = true;
                saveOptions.Password = "password";
                saveOptions.Protection = new WordProcessingProtection(WordProcessingProtectionType.ReadOnly, "write_password");

                using (FileStream outputStream = File.Create("filepath/editedDocument.docx"))
                {
                    editor.Save(afterEdit, outputStream, saveOptions);
                }
            }
        }
    }
}

다음은 위의 코드를 사용하여 모든 발생을 대체한 출력 문서입니다.

편집기 API를 사용하여 편집된 docx 문서

출력 문서 - 모든 항목이 대체됩니다.

결론

결론적으로 .NET 응용 프로그램용 문서 편집 API를 사용하여 C#에서 Word 문서를 편집하는 방법에 대해 논의했습니다. 문서의 시각적 편집을 위해 WYSIWYG 편집기와 함께 API를 사용할 수 있습니다. 그 후에는 자신만의 문서 편집기를 구축할 수 있습니다. 마찬가지로 .NET 응용 프로그램 내에서 편집 기능을 통합할 수도 있습니다.

자세한 내용, 옵션 및 예제를 보려면 문서GitHub 저장소를 방문하십시오. 추가 문의 사항은 포럼의 지원팀에 문의하세요.

관련 기사

또한보십시오