none
OpenXML WordprocessingML throwing parts missing or invalid error RRS feed

  • Question

  • I am working on the code to write out the document into xml and save it into a docx package.   The code does create the document correctly, however when I open the document it tells me that  ‘Microsoft Office cannot open this file because some parts are missing or invalid.”   I have tried to open the document created with the Open XML SDK 2.0 Productivity Tool for Microsoft Office but that also tells me ‘Cannot open the file: The specified file type is not supported’.   I’m unsure why I am receiving this error as the document is .docx.   When I unzip the file it creates a _rels directory with .rels file inside, a word direcoty with document.xml inside, and a [Content_Type].xml file in the root.   Below is my code for generating the document.  Any help would be greatly appreciated!

     

      Protected Sub hlBarcodeDocument_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles hlBarcodeDocument.Click
        Dim filepath As String
    
    
    
        filepath = "wwwroot/TrackUnits/BarcodeImages/" & Guid.NewGuid.ToString() & ".docx"
    
        CreateXMLDocument(filepath)
        ReturnStream(filepath)
    
      End Sub
    
    _______________________________________________________________________________________________________________
    
     Private Sub ReturnStream(ByVal filepath As String)
        Dim iStream As System.IO.Stream
    
        ' Buffer to read 10K bytes in chunk:
        Dim buffer(10000) As Byte
    
        ' Length of the file:
        Dim length As Integer
    
        ' Total bytes to read:
        Dim dataToRead As Long
    
        ' Identify the file to download including its path.
        'filepath = "C:\OpenXML1\sanjay.docx"
    
        ' Identify the file name.
        Dim filename As String = System.IO.Path.GetFileName(filepath)
    
        Try
          ' Open the file.
          iStream = New System.IO.FileStream(filepath, _
               System.IO.FileMode.Open, IO.FileAccess.Read, _
               IO.FileShare.Read)
    
          ' Total bytes to read:
          dataToRead = iStream.Length
    
          Response.ContentType = "application/vnd.ms-word.document.12"
          'Response.ContentType = "application/octet-stream"
          Response.AddHeader("Content-Disposition", _
            "attachment; filename=" & filename)
    
          ' Read the bytes.
          While dataToRead > 0
            ' Verify that the client is connected.
            If Response.IsClientConnected Then
              ' Read the data in buffer
              length = iStream.Read(buffer, 0, 10000)
    
              ' Write the data to the current output stream.
              Response.OutputStream.Write(buffer, 0, length)
    
              ' Flush the data to the HTML output.
              Response.Flush()
    
              ReDim buffer(10000) ' Clear the buffer
              dataToRead = dataToRead - length
            Else
              'prevent infinite loop if user disconnects
              dataToRead = -1
            End If
          End While
    
        Catch ex As Exception
          ' Trap the error, if any.
          Response.Write("Error : " & ex.Message)
        Finally
          If IsNothing(iStream) = False Then
            ' Close the file.
            iStream.Close()
          End If
        End Try
      End Sub
    
    _____________________________________________________________________________________________________
    
    
     Public Sub CreateXMLDocument(ByVal filepath As String)
    
    
        Dim doc As XmlDocument
        doc = New XmlDocument()
        
    
    
        'Create Beginning of XML template
        Dim st As New StringBuilder
        st.Append("<?xml version='1.0' encoding='UTF-8' standalone='yes'?>")
        st.Append("<?mso-application progid='Word.Document'?>")
        st.Append("<w:wordDocument xmlns:w='http://schemas.microsoft.com/office/word/2006/wordml' xmlns:o='urn:schemas-microsoft-com:office:office'>")
        st.Append("<o:DocumentProperties> <!-- generic office document properties --> </o:DocumentProperties>")
        st.Append("<w:fonts> <!-- fonts used in document --> </w:fonts>")
        st.Append("<w:styles> <!-- named styles used in document --> </w:styles>")
        st.Append("<w:docPr> <!-- Word-specific document properties --> </w:docPr>")
        st.Append("<w:body>")
        st.Append("<w:tbl>")
        st.Append("<w:tblPr>")
        st.Append("<w:tblW w:w='12150' w:type='dxa'/>")
        st.Append("<w:tblInd w:w='115' w:type='dxa'/>")
        st.Append("<w:tblLayout w:type='fixed'/>")
        st.Append("<w:tblCellMar>")
        st.Append("<w:left w:w='115' w:type='dxa'/>")
        st.Append("<w:right w:w='115' w:type='dxa'/>")
        st.Append("</w:tblCellMar>")
        st.Append("<w:tblLook w:val='0000'/>")
        st.Append("</w:tblPr>")
        st.Append("<w:tblGrid>")
        st.Append("<w:gridCol w:w='4050'/>")
        st.Append("<w:gridCol w:w='4050'/>")
        st.Append("<w:gridCol w:w='4050'/>")
        st.Append("</w:tblGrid>")
    
        'Loop through barcodes in DV to create and fill cells and rows
    
    
        Dim DV1 As DataView = GetData()
        If Not IsNothing(DV1) Then
          If DV1.Count > 0 Then
            Dim ImgID As Int32 = 1
            Dim i As Integer = 1
            Dim j As Integer = 1
            Dim k As Integer
            While i <= DV1.Count
    
            
    
    
              st.Append("<w:tr w:rsidR='007D3191' w:rsidRPr='00717326' w:rsidTr='00A10DBB'>")
              st.Append("<w:trPr>")
              st.Append("<w:trHeight w:hRule='exact' w:val='1980'/>")
              st.Append("</w:trPr>")
    
    
    
    
              For k = 1 To 3
                If i <= DV1.Count Then
                  Dim ProjectID As String = DV1.Table.Rows(i - 1).Item("ProjectID").ToString()
                  Dim UnitNo As String = DV1.Table.Rows(i - 1).Item("UnitNumber").ToString()
                  Dim RemakeNo As String = DV1.Table.Rows(i - 1).Item("RemakeNo").ToString()
    
    
    
    
                  'Check if barcode image exists.
                  Dim barcodeText As String = "A" & AddZeroesAtBeginning(ProjectID, 5) & AddZeroesAtBeginning(UnitNo, 6) & RemakeNo
                  Dim barcodeFileName As String = "BarcodeImages/" & barcodeText & ".png"
                  Dim BarcodeServerPath As String = Server.Mappath(barcodeFileName)
                  If File.Exists(BarcodeServerPath) = False Then
                    Dim tmpBarcode As System.Drawing.Image = GenerateBarCode128Alternate2(barcodeText)
    
                    ' tmpBarcode.Save(barcodeFileName, System.Drawing.Imaging.ImageFormat.Png)
                    'Dim bcImg = oDoc.Tables.Item(1).Cell(j, k).Range.InlineShapes.AddPicture(barcodeTempFileName)
                    'bcImg.Width = 150
                  End If
    
    
                
    
    
                  st.Append("<w:tc>")
                  st.Append("<w:tcPr>")
                  st.Append("<w:tcW w:w='4050' w:type='dxa'/>")
                  st.Append("<w:tcMar>")
                  st.Append("<w:top w:w='0' w:type='dxa'/>")
                  st.Append("<w:bottom w:w='0' w:type='dxa'/>")
                  st.Append("</w:tcMar>")
                  st.Append("<w:vAlign w:val='center'/>")
                  st.Append("</w:tcPr>")
                  st.Append("<w:p w:rsidR='00202CAF' w:rsidRDefault='00202CAF'>")
                  st.Append("<w:pPr>")
                  st.Append("<w:pStyle w:val='AveryStyle1'/>")
                  st.Append("<w:contextualSpacing/>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("</w:pPr>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:noProof/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
    
    
    
    
    
    
    
                  '<w:drawing>
                  ' <wp:inline distT="0" distB="0" distL="0" distR="0">
                  '  <wp:extent cx="1905000" cy="381000"/>
                  '  <wp:effectExtent l="19050" t="0" r="0" b="0"/>
                  '  <wp:docPr id="1" name="Picture 1"/>
                  '  <wp:cNvGraphicFramePr/>
                  '  <a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
                  '   <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
                  '    <pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
                  '     <pic:nvPicPr>
                  '      <pic:cNvPr id="0" name=""/>
                  '      <pic:cNvPicPr/>
                  '     </pic:nvPicPr>
                  '     <pic:blipFill>
                  '      <a:blip r:embed="rId5"/>
                  '      <a:stretch>
                  '       <a:fillRect/>
                  '      </a:stretch>
                  '     </pic:blipFill>
                  '     <pic:spPr>
                  '      <a:xfrm>
                  '       <a:off x="0" y="0"/>
                  '       <a:ext cx="1905000" cy="381000"/>
                  '      </a:xfrm>
                  '      <a:prstGeom prst="rect">
                  '       <a:avLst/>
                  '      </a:prstGeom>
                  '     </pic:spPr>
                  '    </pic:pic>
                  '   </a:graphicData>
                  '  </a:graphic>
                  ' </wp:inline>
                  '</w:drawing>
    
    
    
    
    
    
                  st.Append("</w:r>")
                  st.Append("</w:p>")
                  st.Append("<w:p w:rsidR='00202CAF' w:rsidRDefault='00202CAF'>")
                  st.Append("<w:pPr>")
                  st.Append("<w:pStyle w:val='AveryStyle1'/>")
                  st.Append("<w:contextualSpacing/>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("</w:pPr>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:t>" & barcodeText & "</w:t>")
                  st.Append("</w:r>")
                  st.Append("</w:p>")
    
    
    
    
    
                  st.Append("<w:p w:rsidR='00202CAF' w:rsidRDefault='00202CAF'>")
                  st.Append("<w:pPr>")
                  st.Append("<w:pStyle w:val='AveryStyle1'/>")
                  st.Append("<w:contextualSpacing/>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("</w:pPr>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  Dim ProjectName As String = DV1.Table.Rows(i - 1).Item("ProjectName").ToString()
                  st.Append("<w:t>" & ProjectName & "</w:t>")
                  st.Append("</w:r>")
                  st.Append("</w:p>")
    
                 
    
    
    
                  st.Append("<w:p w:rsidR='00202CAF' w:rsidRDefault='00202CAF'>")
                  st.Append("<w:pPr>")
                  st.Append("<w:pStyle w:val='AveryStyle1'/>")
                  st.Append("<w:contextualSpacing/>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("</w:pPr>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:t>Style:</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  Dim StyleName As String = DV1.Table.Rows(i - 1).Item("StyleName").ToString()
                  st.Append("<w:t>" & StyleName & "</w:t>")
                  st.Append("</w:r>")
                  st.Append("</w:p>")
    
    
                
    
                  st.Append("<w:p w:rsidR='00202CAF' w:rsidRDefault='00202CAF'>")
                  st.Append("<w:pPr>")
                  st.Append("<w:pStyle w:val='AveryStyle1'/>")
                  st.Append("<w:contextualSpacing/>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("</w:pPr>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:t>Unit:</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  st.Append("<w:t>" & UnitNo & "</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  st.Append("<w:t>Priority:</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  Dim Priority As String = DV1.Table.Rows(i - 1).Item("Priority").ToString()
                  st.Append("<w:t>" & Priority & "</w:t>")
                  st.Append("</w:r>")
                  st.Append("</w:p>")
    
    
    
                 
    
    
    
                  st.Append("<w:p w:rsidR='00202CAF' w:rsidRDefault='00202CAF'>")
                  st.Append("<w:pPr>")
                  st.Append("<w:pStyle w:val='AveryStyle1'/>")
                  st.Append("<w:contextualSpacing/>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("</w:pPr>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:t>Order#:</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  Dim OrderNumber As String = DV1.Table.Rows(i - 1).Item("OrderNumber").ToString()
                  st.Append("<w:t>" & OrderNumber & "</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  st.Append("<w:t>Elevation:</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  Dim Elevation As String = DV1.Table.Rows(i - 1).Item("Elevation").ToString()
                  st.Append("<w:t>" & Elevation & "</w:t>")
                  st.Append("</w:r>")
                  st.Append("</w:p>")
    
                
    
                  st.Append("<w:p w:rsidR='007D3191' w:rsidRPr='00717326' w:rsidRDefault='00202CAF'>")
                  st.Append("<w:pPr>")
                  st.Append("<w:pStyle w:val='AveryStyle1'/>")
                  st.Append("<w:contextualSpacing/>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("</w:pPr>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:t>Drop:</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  Dim Drop As String = DV1.Table.Rows(i - 1).Item("Drop").ToString()
                  st.Append("<w:t>" & Drop & "</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  st.Append("<w:t>Dwg:</w:t>")
                  st.Append("</w:r>")
                  st.Append("<w:r>")
                  st.Append("<w:rPr>")
                  st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana'/>")
                  st.Append("<w:sz w:val='10'/>")
                  st.Append("<w:szCs w:val='10'/>")
                  st.Append("</w:rPr>")
                  st.Append("<w:tab/>")
                  Dim DrawingNumber As String = DV1.Table.Rows(i - 1).Item("DrawingNumber").ToString()
                  st.Append("<w:t>" & DrawingNumber & "</w:t>")
                  st.Append("</w:r>")
                  st.Append("</w:p>")
                  st.Append("</w:tc>")
    
                  i += 1
                End If
                ImgID += 1
              Next
              'j += 1
              'If j > 8 Then
              '  oDoc.Tables.Item(1).Rows.Add()
              'End If
              st.Append("</w:tr>")
    
            End While
          End If
        End If
    
    
    
    
    
    
    
    
        'End of XML data
    
        
    
        st.Append("</w:tbl>")
        st.Append("<w:p w:rsidR='007D3191' w:rsidRPr='00717326' w:rsidRDefault='007D3191'>")
        st.Append("<w:pPr>")
        st.Append("<w:spacing w:after='0' w:line='20' w:lineRule='exact'/>")
        st.Append("<w:contextualSpacing/>")
        st.Append("<w:rPr>")
        st.Append("<w:rFonts w:ascii='Verdana' w:hAnsi='Verdana' w:cs='Arial'/>")
        st.Append("<w:sz w:val='10'/>")
        st.Append("<w:szCs w:val='10'/>")
        st.Append("</w:rPr>")
        st.Append("</w:pPr>")
        st.Append("</w:p>")
        st.Append("<w:sectPr w:rsidR='007D3191' w:rsidRPr='00717326' w:rsidSect='007D3191'>")
        st.Append("<w:pgSz w:w='12240' w:h='15840'/>")
        st.Append("<w:pgMar w:top='1' w:right='446' w:bottom='0' w:left='170' w:header='0' w:footer='0' w:gutter='0'/>")
        st.Append("<w:cols w:space='720'/>")
        st.Append("<w:docGrid w:linePitch='360'/>")
        st.Append("</w:sectPr>")
        st.Append("</w:body>")
        st.Append("</w:wordDocument>")
    
    
    
        doc.LoadXml(st.ToString)
    
        'Create Package
        Dim _Package As Package
    
        _Package = Package.Open(filepath, FileMode.Create, FileAccess.ReadWrite)
    
        Dim _uri As Uri
    
        _uri = New Uri("/word/document.xml", UriKind.Relative)
    
        Dim part As PackagePart
        part = _Package.CreatePart(_uri, "application/vnd.ms-word.main+xml")
    
        Dim partWrt As StreamWriter
        partWrt = New StreamWriter(part.GetStream(FileMode.Create, FileAccess.Write))
        doc.Save(partWrt)
        partWrt.Close()
        _Package.Flush()
    
    
        'Create Relationship
        _uri = New Uri("/word/document.xml", UriKind.Relative)
        Dim rel As PackageRelationship
        rel = _Package.CreateRelationship(_uri, TargetMode.Internal, "http://schemas.microsoft.com/office/2006/relationships/officeDocument", "rId1")
    
        _Package.Flush()
        _Package.Close()
    
    
    
    
    
      End Sub
    

    Thursday, January 27, 2011 9:06 PM

Answers

  • Hi ACG_JC,

    Thank you for posting and we are glad to help with you.

    Have you resolved your issue yet? After reading your post, I tested with you code and also encountered the same issue.

    What's the version of your office? I use Office2010. I have spent a lot of time to research your issue, but I haven't fixed your issue. I think it may be related with the wrong content of the xml file or the namespace. I succeeded in generating word2010 document with the following code. It is not the same with your code, but I think it may help you:

    Imports DocumentFormat.OpenXml
    Imports System.Xml
    Imports System.Text
    Imports System.IO
    Imports System.IO.Packaging
    Public Class Form1

        Private Sub Button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgsHandles Button1.Click
            Dim filepath As String
            filepath = AppDomain.CurrentDomain.BaseDirectory & Guid.NewGuid.ToString() & ".docx"
            CreateXMLDocument(filepath)
        End Sub

        Public Sub CreateXMLDocument(ByVal filepath As String)

            '-- Step 1 - Creating the document xml
            Dim _nameSpaceURI As String = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
            Dim doc As New XmlDocument()
            Dim _wWordDoc As XmlElement = doc.CreateElement("w:wordDocument", _nameSpaceURI)
            doc.AppendChild(_wWordDoc)
            Dim _wbody As XmlElement = doc.CreateElement("w:body", _nameSpaceURI)
            _wWordDoc.AppendChild(_wbody)

            For row As Integer = 0 To 1
                Dim _wp1 As XmlElement = doc.CreateElement("w:p", _nameSpaceURI)
                _wbody.AppendChild(_wp1)
                Dim _wr1 As XmlElement = doc.CreateElement("w:r", _nameSpaceURI)
                _wp1.AppendChild(_wr1)
                Dim _wt11 As XmlElement = doc.CreateElement("w:t", _nameSpaceURI)
                _wr1.AppendChild(_wt11)
                Dim _wt1 As XmlNode = doc.CreateNode(XmlNodeType.Text, "w:t", _nameSpaceURI)
                _wt1.Value = "Test"
                _wt11.AppendChild(_wt1)
            Next

            'Create Package
            Dim _Package As Package

            _Package = Package.Open(filepath, FileMode.Create, FileAccess.ReadWrite)

            Dim _uri As Uri

            _uri = New Uri("/word/document.xml"UriKind.Relative)

            Dim part As PackagePart
            ' part = _Package.CreatePart(_uri, "application/vnd.ms-word.main+xml")
            part = _Package.CreatePart(_uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml")

            Dim partWrt As StreamWriter
            partWrt = New StreamWriter(part.GetStream(FileMode.Create, FileAccess.Write))
            doc.Save(partWrt)
            partWrt.Close()
            _Package.Flush()


            'Create Relationship
            _uri = New Uri("/word/document.xml"UriKind.Relative)
            Dim rel As PackageRelationship
            'rel = _Package.CreateRelationship(_uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "rId1")
            rel = _Package.CreateRelationship(_uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument""rId1")

            _Package.Flush()
            _Package.Close()
        End Sub

        'Private Function GetData() As DataView
        '    Dim dv As New DataView
        '    Dim dt As New DataTable
        '    Dim arr() As String = {"ID1", "UnitNum1", "RemarkNo1", "DrawingNumber1", "Drop1", "Elevation1", "Priority1", "StyleName1", "ProjectName1", "OrderNumber1"}
        '    dt.Columns.Add("ProjectID")
        '    dt.Columns.Add("UnitNumber")
        '    dt.Columns.Add("RemakeNo")
        '    dt.Columns.Add("DrawingNumber")
        '    dt.Columns.Add("Drop")
        '    dt.Columns.Add("Elevation")
        '    dt.Columns.Add("Priority")
        '    dt.Columns.Add("StyleName")
        '    dt.Columns.Add("ProjectName")
        '    dt.Columns.Add("OrderNumber")

        '    dt.Rows.Add(arr)
        '    dt.Rows.Add(arr)
        '    Return dt.DefaultView
        'End Function
    End Class

    Could it be the reason of openxml namespace? The Office2010 namespace seems to be different with Office2007. I can only give you such directions. I hope it can help you and feel free to follow up after you have researched.

    Best Regards,

     


    Bruce Song [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Bessie Zhao Tuesday, February 8, 2011 9:17 AM
    Tuesday, February 1, 2011 7:45 AM
  • Hi Bruce,

     

    Thank you very much for looking into the issue!  After taking your lead and a lot of tearing my hair out I've found that the template I was referencing when I created this XML document was in fact a Word 2003 template.   I was able to update the code a little bit by changing the namespace to 2003 and adding double quotes around the Word Document XML call as follows:

    st.Append("?mso-application progid=""Word.Document""?>")

    st.Append("<w:wordDocument xmlns:w='http://schemas.microsoft.com/office/word/2003/wordml' xmlns:o='urn:schemas-microsoft-com:office:office'>")

     

    I then had to save the xml document to a .doc file instead of a .docx file.   This seemed to finally resolve the issue!

    Thank you Bruce, I really appreciate you taking the time to look into this issue for me!  Hopefully this post can help others too!

     

    Thanks again,

    ACG_JC

    • Marked as answer by Bessie Zhao Tuesday, February 8, 2011 9:17 AM
    Tuesday, February 1, 2011 4:50 PM

All replies

  • Hi ACG_JC,

    Thank you for posting and we are glad to help with you.

    Have you resolved your issue yet? After reading your post, I tested with you code and also encountered the same issue.

    What's the version of your office? I use Office2010. I have spent a lot of time to research your issue, but I haven't fixed your issue. I think it may be related with the wrong content of the xml file or the namespace. I succeeded in generating word2010 document with the following code. It is not the same with your code, but I think it may help you:

    Imports DocumentFormat.OpenXml
    Imports System.Xml
    Imports System.Text
    Imports System.IO
    Imports System.IO.Packaging
    Public Class Form1

        Private Sub Button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgsHandles Button1.Click
            Dim filepath As String
            filepath = AppDomain.CurrentDomain.BaseDirectory & Guid.NewGuid.ToString() & ".docx"
            CreateXMLDocument(filepath)
        End Sub

        Public Sub CreateXMLDocument(ByVal filepath As String)

            '-- Step 1 - Creating the document xml
            Dim _nameSpaceURI As String = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
            Dim doc As New XmlDocument()
            Dim _wWordDoc As XmlElement = doc.CreateElement("w:wordDocument", _nameSpaceURI)
            doc.AppendChild(_wWordDoc)
            Dim _wbody As XmlElement = doc.CreateElement("w:body", _nameSpaceURI)
            _wWordDoc.AppendChild(_wbody)

            For row As Integer = 0 To 1
                Dim _wp1 As XmlElement = doc.CreateElement("w:p", _nameSpaceURI)
                _wbody.AppendChild(_wp1)
                Dim _wr1 As XmlElement = doc.CreateElement("w:r", _nameSpaceURI)
                _wp1.AppendChild(_wr1)
                Dim _wt11 As XmlElement = doc.CreateElement("w:t", _nameSpaceURI)
                _wr1.AppendChild(_wt11)
                Dim _wt1 As XmlNode = doc.CreateNode(XmlNodeType.Text, "w:t", _nameSpaceURI)
                _wt1.Value = "Test"
                _wt11.AppendChild(_wt1)
            Next

            'Create Package
            Dim _Package As Package

            _Package = Package.Open(filepath, FileMode.Create, FileAccess.ReadWrite)

            Dim _uri As Uri

            _uri = New Uri("/word/document.xml"UriKind.Relative)

            Dim part As PackagePart
            ' part = _Package.CreatePart(_uri, "application/vnd.ms-word.main+xml")
            part = _Package.CreatePart(_uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml")

            Dim partWrt As StreamWriter
            partWrt = New StreamWriter(part.GetStream(FileMode.Create, FileAccess.Write))
            doc.Save(partWrt)
            partWrt.Close()
            _Package.Flush()


            'Create Relationship
            _uri = New Uri("/word/document.xml"UriKind.Relative)
            Dim rel As PackageRelationship
            'rel = _Package.CreateRelationship(_uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "rId1")
            rel = _Package.CreateRelationship(_uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument""rId1")

            _Package.Flush()
            _Package.Close()
        End Sub

        'Private Function GetData() As DataView
        '    Dim dv As New DataView
        '    Dim dt As New DataTable
        '    Dim arr() As String = {"ID1", "UnitNum1", "RemarkNo1", "DrawingNumber1", "Drop1", "Elevation1", "Priority1", "StyleName1", "ProjectName1", "OrderNumber1"}
        '    dt.Columns.Add("ProjectID")
        '    dt.Columns.Add("UnitNumber")
        '    dt.Columns.Add("RemakeNo")
        '    dt.Columns.Add("DrawingNumber")
        '    dt.Columns.Add("Drop")
        '    dt.Columns.Add("Elevation")
        '    dt.Columns.Add("Priority")
        '    dt.Columns.Add("StyleName")
        '    dt.Columns.Add("ProjectName")
        '    dt.Columns.Add("OrderNumber")

        '    dt.Rows.Add(arr)
        '    dt.Rows.Add(arr)
        '    Return dt.DefaultView
        'End Function
    End Class

    Could it be the reason of openxml namespace? The Office2010 namespace seems to be different with Office2007. I can only give you such directions. I hope it can help you and feel free to follow up after you have researched.

    Best Regards,

     


    Bruce Song [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Bessie Zhao Tuesday, February 8, 2011 9:17 AM
    Tuesday, February 1, 2011 7:45 AM
  • Hi Bruce,

     

    Thank you very much for looking into the issue!  After taking your lead and a lot of tearing my hair out I've found that the template I was referencing when I created this XML document was in fact a Word 2003 template.   I was able to update the code a little bit by changing the namespace to 2003 and adding double quotes around the Word Document XML call as follows:

    st.Append("?mso-application progid=""Word.Document""?>")

    st.Append("<w:wordDocument xmlns:w='http://schemas.microsoft.com/office/word/2003/wordml' xmlns:o='urn:schemas-microsoft-com:office:office'>")

     

    I then had to save the xml document to a .doc file instead of a .docx file.   This seemed to finally resolve the issue!

    Thank you Bruce, I really appreciate you taking the time to look into this issue for me!  Hopefully this post can help others too!

     

    Thanks again,

    ACG_JC

    • Marked as answer by Bessie Zhao Tuesday, February 8, 2011 9:17 AM
    Tuesday, February 1, 2011 4:50 PM
  • I've created the following code and I'm getting the same error 'microsoft office cannot open this file because some parts are missing or invalid'

    Does anyone knows what am I doing wrong? I'm using the latest available version of OpenXML SDK 2.0

     Thanks a lot

                WordprocessingDocument wordDocument = WordprocessingDocument.Create(@"C:\Doctests\POC.docx"WordprocessingDocumentType.Document);
                // Add a main document part. 
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
     
                // Create the document structure and add some text.
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                Paragraph para = body.AppendChild(new Paragraph());
                Run run = para.AppendChild(new Run());
                run.AppendChild(new Text("Create text in body - CreateWordprocessingDocument"));
     
             
                mainPart.Document.Save();

    Mauro Zamaro .:
    • Proposed as answer by Mauro Zamaro Friday, October 21, 2011 3:28 PM
    • Unproposed as answer by Mauro Zamaro Friday, October 21, 2011 3:28 PM
    Thursday, July 28, 2011 2:54 PM
  • I found my mistake

     

     

                using (WordprocessingDocument CurrentDocument = Open())
                {
                    if (CurrentDocument != null)
                    {
                        Paragraph p = new Paragraph();
                        Run r = new Run();
                        Text t = new Text();
                        t.Text = strText;
                        r.AppendChild(t);
                        p.AppendChild(r);
                        CurrentDocument.MainDocumentPart.Document.Body.AppendChild(p);
                        CurrentDocument.MainDocumentPart.Document.Save(); // i have to save each paragraph added to the part.
                    }
    

    where

     

    Open() is like :

     

     protected WordprocessingDocument Open()
            {
                OpenSettings openSettings = new OpenSettings();
    
                openSettings.MarkupCompatibilityProcessSettings =
                    new MarkupCompatibilityProcessSettings(
                        MarkupCompatibilityProcessMode.ProcessAllParts,
                        FileFormatVersions.Office2007);
                WordprocessingDocument ojbReturn;
                if (File.Exists(FullPath))
                {
                    ojbReturn = WordprocessingDocument.Open(FullPath, true,openSettings); // create an open doc element from loaded InternalCache.
                 }
                 return ojbReturn;
            }
    

     

     

     

    but if you want to create a new blank document you may want to use something like this:

    using (WordprocessingDocument CurrentDocument = WordprocessingDocument.Create(FullPath, WordprocessingDocumentType.Document,true))
                {
                    MainDocumentPart mMainPart = CurrentDocument.AddMainDocumentPart();
                    // prepare the document to render table styles
                    StylesWithEffectsPart stylesWithEffectsPart1 = mMainPart.AddNewPart<StylesWithEffectsPart>("rId2");
                    DocumentTableStyle.GenerateStylesWithEffectsPart1Content(stylesWithEffectsPart1);
                    StyleDefinitionsPart styleDefinitionsPart1 = mMainPart.AddNewPart<StyleDefinitionsPart>("rId1");
                    DocumentTableStyle.GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1);
                    NumberingDefinitionsPart numberingDefinitionsPart1 = mMainPart.AddNewPart<NumberingDefinitionsPart>("rIdn");
                    DocumentBasicFormatting.GenerateNumberingDefinitionsPart1Content(numberingDefinitionsPart1);
                    //Creating a new document 
                    mMainPart.Document = new Document();
                    //other elements that we want to include 
                    Body body = new Body();
                    //Create paragraph 
                    Paragraph paragraph = new Paragraph();
                    Run run_paragraph = new Run();
                    // we want to put that text into the output document 
                    Text text_paragraph = new Text();
                    //Append elements appropriately. 
                    run_paragraph.Append(text_paragraph);
                    paragraph.Append(run_paragraph);
                    body.Append(paragraph);
                    mMainPart.Document.Append(body);
                    // Save changes to the main document part. 
                    mMainPart.Document.Save();
                }

     

     

     

     

     


    Mauro Zamaro .:
    • Proposed as answer by Mauro Zamaro Friday, October 21, 2011 3:31 PM
    • Edited by Mauro Zamaro Friday, October 21, 2011 3:34 PM
    Friday, October 21, 2011 3:31 PM