Open XML 개체 모델을 사용하여 Office Open XML 패키지 생성하기
[이 글은 프리릴리스 문서로, 출시 후에 변경될 가능성이 있습니다.]
Office Open XML 패키지의 사양은 컨텐츠를 포함하여, 단일 패키지에 보관된 모든 파트의 관계를 정의하는 XML 파일집합을 정의합니다. 이러한 패키지는 Microsoft Office Excel 2007, Microsoft Office PowerPoint 2007 및 Microsoft Office Word 2007 의 문서 파일을 구성하는 파트를 결합니다. Open XML 개체 모델을 사용하고, 패키지를 생성하거나 패키지를 구성하는 파일을 조작할 수 있습니다. 이 토픽에서는 Word 2007에서 Office Open XML 패키지를 생성하기 위한 코드와 순서에 대해서만 설명하는데, 방식은 Office Open XML 형식을 지원하는 세 가지의 2007 Office system 프로그램과 같습니다.
메모 : |
---|
이 토픽의 코드견본은 Visual Basic .NET 및 Visual C# 로 Microsoft Visual Studio 2008 에서 생성된 추가기능으로 사용할 수 있습니다. Visual Studio 2008에서의 추가 기능 생성 순서는 이 시리즈의 「Microsoft SDK for Open XML Formats 를 사용하여 작업 시작하기」에서 볼 수 있습니다. |
Office Open XML 형식의 패키지 생성하기
다음 코드에서는 Office Open XML 패키지를 생성합니다.
Visual Basic
Public Sub CreateNewWordDocument(ByVal document As String)
Dim wordDoc As WordprocessingDocument = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document)
Using (wordDoc)
' Set the content of the document so that Word can open it.
Dim mainPart As MainDocumentPart = wordDoc.AddMainDocumentPart
SetMainDocumentContent(mainPart)
End Using
End Sub
Public Sub SetMainDocumentContent(ByVal part As MainDocumentPart)
Const docXml As String = "<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>" & _
"<w:document xmlns:w=""https://schemas.openxmlformats.org/wordprocessingml/2006/main"">" & _
"<w:body><w:p><w:r><w:t>Hello world!</w:t></w:r></w:p></w:body></w:document>"
Dim stream1 As Stream = part.GetStream
Dim utf8encoder1 As UTF8Encoding = New UTF8Encoding()
Dim buf() As Byte = utf8encoder1.GetBytes(docXml)
stream1.Write(buf, 0, buf.Length)
End Sub
// How to: Create a new package as a Word document.
public static void CreateNewWordDocument(string document)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document))
{
// Set the content of the document so that Word can open it.
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
SetMainDocumentContent(mainPart);
}
}
// Set content of MainDocumentPart.
public static void SetMainDocumentContent(MainDocumentPart part)
{
const string docXml =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<w:document xmlns:w=""https://schemas.openxmlformats.org/wordprocessingml/2006/main"">
<w:body><w:p><w:r><w:t>Hello world!</w:t></w:r></w:p></w:body>
</w:document>";
using (Stream stream = part.GetStream())
{
byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
stream.Write(buf, 0, buf.Length);
}
}
먼저 Word 2007 문서의 경로와 그 이름을 나타내는 매개 변수를 건네줍니다. 그리고, 입력 문서의 이름에 근거하여, 패키지를 나타내는 WordprocessingDocument 개체를 생성합니다. 그리고, AddMainDocumentPart 메서드가 호출되어 메인 문서 파트를 /word/document.xml 로 새로운 패키지에 생성합니다. 마지막으로, SetMainDocumentContent 메서드가 호출되어 생성한 메인 문서 파트를 설정합니다.