使用OpenXML声明WordprocessingDocument的新实例

时间:2013-05-15 03:18:16

标签: .net vb.net openxml openxml-sdk

我第一次尝试使用开放式XML。我正在按照http://www.codeproject.com/Articles/36694/Creation-of-a-Word-2007-document-using-the-Open-XM中的教程进行操作。当我将变量声明为新WordprocessingDocument时,我收到错误:

  

“类型WordprocessingDocument.Create未定义”。

Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Wordprocessing
Imports DocumentFormat.OpenXml.Packaging

Partial Class test

Public Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    makedoc("file.docx")
End Sub

Private Sub makedoc(ByVal documentfilename As String)
    Using mydoc As New WordprocessingDocument.Create(documentfilename, WordprocessingDocumentType.Document)
        Dim mainPart As MainDocumentPart = mydoc.AddMainDocumentPart()
        'Create Document tree for simple document. 
        mainPart.Document = New Document()
        'Create Body (this element contains
        'other elements that we want to include 
        Dim body As New Body()
        'Create paragraph 
        Dim paragraph As New Paragraph()
        Dim run_paragraph As New Run()
        ' we want to put that text into the output document 
        Dim text_paragraph As New Text("Hello World!")
        'Append elements appropriately. 
        run_paragraph.Append(text_paragraph)
        paragraph.Append(run_paragraph)
        body.Append(paragraph)
        mainPart.Document.Append(body)
        ' Save changes to the main document part. 
        mainPart.Document.Save()
    End Using

1 个答案:

答案 0 :(得分:1)

您无法像这样创建WordDocumentProcessing的新实例。构造函数受到保护。

您需要调用CreateOpen方法:

Using mydoc as WordProcessingDocument = WordProcessingDocument.Create(DocumentFileName, WordprocessingDocumentType.Document)
   ...
End Using