어떤 사람들은 Microsoft Office Interop 라이브러리를 사용하여 Word 문서를 만들지만 종종 Interop 없이 C#에서 Word 문서를 만드는 방법을 묻습니다. 여기에서 Aspose.Words for .NET이(가) C#에서 Word 문서를 쉽게 만들 수 있도록 도와줍니다.
이 질문은 C# 코드 샘플과 함께 아래 단계에서 답변됩니다. 이것은 .NET 콘솔 유틸리티, Windows 애플리케이션, ASP.NET 웹 프로젝트 등 .NET 애플리케이션에서 처음부터 DOCX 또는 DOC 파일을 얼마나 쉽고 효율적으로 생성할 수 있는지 보여줍니다. Aspose.Words는 모든 .NET 플랫폼 기술과 원활하게 작동합니다.
자동화 없이 C#에서 Word 문서를 만드는 단계
- Aspose.Words for .NET NuGet 패키지 사용
- Aspose.Words namespace에 대한 참조 추가
- SetLicense 메서드를 사용하여 Aspose 라이선스 적용
- 새 Document Class 인스턴스 만들기
- DocumentBuilder Class 객체를 만들고 생성자에 Document 객체를 전달합니다.
- DocumentBuilder 개체의 필수 속성 설정
- 출력 Word 문서를 파일 또는 스트림으로 저장
자동화 없이 C#에서 Word 문서를 만드는 코드
using System; | |
//Add reference to Aspose.Words for .NET API | |
//Use following namespaces to Word Document generator code | |
using Aspose.Words; | |
namespace CreateWordDocumentWithoutInterop | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before creating Word document without Interop | |
//using Aspose.Words for .NET | |
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License(); | |
AsposeWordsLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//Create an instance of Document class of Aspose.Words for .NET | |
//This initiates a blank Word document | |
Document WordDocumentWithoutInterop = new Document(); | |
//An instance of DocumentBuilder class is used to add | |
//content to the Word Document | |
DocumentBuilder WordDocumentBuilder = new DocumentBuilder(WordDocumentWithoutInterop); | |
//Add some text with bold formatting | |
WordDocumentBuilder.Bold = true; | |
WordDocumentBuilder.Writeln("We're adding this line of text in the word document using DocumentBuilder Class"); | |
WordDocumentBuilder.Writeln("This does not require Office Interop or Office Automation"); | |
//Finally, save the generated word document to docx format | |
WordDocumentWithoutInterop.Save("Word_Document_Created_Without_Interop_using_CSharp.docx"); | |
} | |
} | |
} |
이 C# 코드 예제에서는 단 두 줄의 텍스트로 간단한 Word document를 만들고 텍스트에 굵게 속성을 적용했습니다. 그러나 테이블, 셀 및 Word Document Object Model (DOM)의 다른 개체를 추가하여 더 많은 작업을 수행하고 위의 코드를 확장할 수 있습니다.
Aspose.Words for .NET API의 위 C# 코드를 실행하기 위해 응용 프로그램이 설치될 컴퓨터나 서버에 Microsoft Word를 설치할 필요가 없습니다. 이렇게 하면 Word 문서를 훨씬 쉽고 빠르게 만들 수 있습니다.