none
Differences in Excel spreadsheet when created from templates (XLTX) RRS feed

  • Question

  • Hi

    In one of my projects I've discovered a strange difference which affects further working with the Excel spreadsheet.

    First I create a new Excel spreadsheet from an existing template (XLTX) file using the following code:

        Public Function XLCreateExcelWbk(ByVal templatePath As String, ByVal workbookPath As String) As String
    
            Dim oldCulture As Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
            System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
            File.Copy(templatePath, workbookPath, True)
            File.SetAttributes(workbookPath, FileAttributes.Normal)
            Using wbok As SpreadsheetDocument = SpreadsheetDocument.Open(workbookPath, True)
                wbok.ChangeDocumentType(SpreadsheetDocumentType.Workbook)
            End Using
            System.Threading.Thread.CurrentThread.CurrentCulture = oldCulture
            Return workbookPath
    
        End Function

    When I compare the new file aith a manually created spreadsheet using Office 2010 the following difference is found in the file.

    Difference

    Is it something in my code or is this "by design"?

    And, most importand, how can I adjust the spreadsheet so that it contains the same XML-code that tha manually created file?

    Thanks in advance


    Best Regards Peter Karlström Midrange AB, Sweden


    Tuesday, May 14, 2013 10:30 AM

Answers

  • Hi Cindy

    It seems I finally have a solution, which fixes the incorrect filenames and relations in the Office file.

    For others with the same problem, I post my sample code which is to be run with a copied template file which DocumentType is changed to document, spreadsheet or /presentation according to my code in the beginning of this post.

    I have used an open source library called Ionic.Zip on CodePlex (DotNetZip Homepage) to handle the zip package, since system.io.packaging doesn't support the [Content_type].xml file in the root of the package.

    In the code below, you can skip the WriteLogg-parts, since this is already implemented code in my project.

    targetTempPath is a temporary foöder which stores the temporary files from unpacking the office file.

    Friend Function WDSetXMLData(ByVal docPath As String, ByVal targetTempPath As String) As Boolean
    
            If Not targetTempPath.EndsWith("\") Then
                targetTempPath = targetTempPath & "\"
            End If
    
            Dim ZipToUnpack As String
            Dim oldName1 As String = "[Content_Types].xml"
            Dim oldName2 As String = "_rels/.rels"
            Dim oldName3 As String = "word/_rels/document2.xml.rels"
            Dim oldName4 As String = "word/document2.xml"
            Dim newName1 As String = targetTempPath & "[Content_Types].xml"
            Dim newName2 As String = targetTempPath & "_rels\.rels"
            Dim newName3 As String = targetTempPath & "word\_rels\document.xml.rels"
            Dim newName4 As String = targetTempPath & "word\document.xml"
            Dim newPath1 As String = ""
            Dim newPath2 As String = "_rels"
            Dim newPath3 As String = "word\_rels\"
            Dim newPath4 As String = "word\"
            Dim funcReturn As Boolean = True
    
            'Delete temp directory
            Try
                If My.Computer.FileSystem.DirectoryExists(targetTempPath) Then
                    My.Computer.FileSystem.DeleteDirectory(targetTempPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
                End If
            Catch ex As Exception
                WriteLogg("Fel vid borttag av temporär mapp " & targetTempPath & ". Fel: " & ex.Message, "WDSetContentType", logFile)
                Return False
                Exit Function
            End Try
    
            'Create new temp directory
            Try
                My.Computer.FileSystem.CreateDirectory(targetTempPath)
            Catch ex As Exception
                WriteLogg("Fel vid skapande av temporär mapp " & targetTempPath & ". Fel: " & ex.Message, "WDSetContentType", logFile)
                Return False
                Exit Function
            End Try
    
            'Make backup copy of original file
            Try
                FileCopy(docPath, targetTempPath & "tmpXMLDoc.docx")
                ZipToUnpack = targetTempPath & "tmpXMLDoc.docx"
            Catch ex As Exception
                WriteLogg("Fel vid säkerhetskopiering av dokument. Fel: " & ex.Message, "WDSetContentType", logFile)
                Return False
                Exit Function
            End Try
    
            'Unpack files
            Try
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName1 Then
                            e.Extract(targetTempPath, ExtractExistingFileAction.OverwriteSilently)
                        End If
                        If e.FileName = oldName2 Then
                            e.Extract(targetTempPath, ExtractExistingFileAction.OverwriteSilently)
                        End If
                        If e.FileName = oldName3 Then
                            e.Extract(targetTempPath, ExtractExistingFileAction.OverwriteSilently)
                        End If
                        If e.FileName = oldName4 Then
                            e.Extract(targetTempPath, ExtractExistingFileAction.OverwriteSilently)
                        End If
                    Next
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid uppackning av dokument. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Change file / [Content_Types].xml
            Try
                Dim infile As String = targetTempPath & "[Content_Types].xml"
                Dim strRead As StreamReader = New StreamReader(infile)
                Dim text As String = strRead.ReadToEnd()
    
                strRead.Close()
                text = text.Replace("/word/document2.xml", "/word/document.xml")
                Dim strWrite As New StreamWriter(infile, False)
    
                strWrite.Write(text)
                strWrite.Close()
            Catch ex As Exception
                WriteLogg("Fel vid ändring av fil [Content_Types].xml. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Change file / _rels/.rels
            Try
                Dim infile As String = targetTempPath & "_rels\.rels"
                Dim strRead As StreamReader = New StreamReader(infile)
                Dim text As String = strRead.ReadToEnd()
    
                strRead.Close()
                text = text.Replace("/word/document2.xml", "/word/document.xml")
                Dim strWrite As New StreamWriter(infile, False)
    
                strWrite.Write(text)
                strWrite.Close()
            Catch ex As Exception
                WriteLogg("Fel vid ändring av fil _rels/.rels. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Rename file / word/_rels/document2.xml.rels
            Try
                Dim tmpfName As String = oldName3.Replace("2", "")
                tmpfName = tmpfName.Replace("/", "\")
                Dim bPos As Int16 = InStrRev(tmpfName, "\")
                If bPos > 0 Then
                    tmpfName = tmpfName.Substring(bPos)
                End If
                Dim tmpoName As String = targetTempPath & oldName3.Replace("/", "\")
                My.Computer.FileSystem.RenameFile(tmpoName, tmpfName)
            Catch ex As Exception
                WriteLogg("Fel vid namnbyte av fil word/_rels/document2.xml.rels. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Rename file / word/document2.xml
            Try
                Dim tmpfName As String = oldName4.Replace("2", "")
                tmpfName = tmpfName.Replace("/", "\")
                Dim bPos As Int16 = InStrRev(tmpfName, "\")
                If bPos > 0 Then
                    tmpfName = tmpfName.Substring(bPos)
                End If
                Dim tmpoName As String = targetTempPath & oldName4.Replace("/", "\")
                My.Computer.FileSystem.RenameFile(tmpoName, tmpfName)
            Catch ex As Exception
                WriteLogg("Fel vid namnbyte av fil word/document2.xml. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Repack files - [Content_Types].xml
            Try
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName1 Then
                            'zip1.UpdateFile(newName1)
                            zip1.RemoveEntry(oldName1)
                            zip1.AddFile(newName1, "")
                            Exit For
                        End If
                    Next
                    zip1.Save(ZipToUnpack)
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid packning av xmlfil [Content_Types].xml. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Repack files - _rels/.rels
            Try
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName2 Then
                            'zip1.UpdateFile(newName2)
                            zip1.RemoveEntry(oldName2)
                            zip1.AddFile(newName2, newPath2)
                            Exit For
                        End If
                    Next
                    zip1.Save(ZipToUnpack)
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid packning av xmlfil _rels/.rels. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Repack files - word/_rels/document2.xml.rels
            Try
    
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName3 Then
                            zip1.RemoveEntry(oldName3)
                            zip1.AddFile(newName3, newPath3)
                            Exit For
                        End If
                    Next
                    zip1.Save(ZipToUnpack)
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid packning av xmlfil word/_rels/document.xml.rels. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Repack files - word/document.xml
            Try
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName4 Then
                            zip1.RemoveEntry(oldName4)
                            zip1.AddFile(newName4, newPath4)
                            Exit For
                        End If
                    Next
                    zip1.Save()
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid packning av word/document.xml. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Copy newfile to old
            Try
                FileCopy(targetTempPath & "tmpXMLDoc.docx", docPath)
            Catch ex As Exception
                WriteLogg("Fel vid kopiering av nytt dokument. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Delete temp directory
            Try
                My.Computer.FileSystem.DeleteDirectory(targetTempPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
            Catch ex As Exception
                WriteLogg("Fel vid borttag av temporär mapp " & targetTempPath & ". Fel: " & ex.Message, "WDSetContentType", logFile)
            End Try
    
            Return True
    Rollback:
    
            'Delete temp directory
            Try
                My.Computer.FileSystem.DeleteDirectory(targetTempPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
            Catch ex As Exception
                WriteLogg("Fel vid borttag av temporär mapp " & targetTempPath & ". Fel: " & ex.Message, "WDSetContentType", logFile)
            End Try
    
            Return False
    
        End Function
    

    This is all based on the fact that there (at the moment) is the same 4 differences in Word, Excel and Powerpoint.
    With no doubt they will change in coming releases from Microsoft, so this is something you have to watch out for in the future.

    Syntax for changes in Excel are for example xl/workbook2.xml, and for Powerpoint ppt/presentation2.xml


    Best Regards Peter Karlström Midrange AB, Sweden

    Friday, July 5, 2013 1:11 PM

All replies

  • Hi Peter,

    Can you show what's the exact difference between 2 two .rels files and .xml file?

    I think it's ok, since the 2 workbook might base on difference template and some infos in them might be different. (a manually created workbook will be generate based on Normal.xlst, I suppose).

    You can use OpenXML SDK productivity tools to see the reflect code of manually created file.

    hth


    with regards, Yuri

    Friday, May 17, 2013 9:17 AM
  • Hi Yuri

    Thanks for your response

    I have used the OpenXML SDK Productivity tool to make the image in my question which shows the difference between the manually and the automatically created spreadsheets using the tolls Compare function.

    The manually created (with Excel 2010) is on the right, and the autocreated from the sample code is on the left.
    Both files are created from the same template file, not Normal.xltx

    The contents of the two files have differences:

    The.rels file of the manually created spreadsheet looks like this:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties" Target="docProps/custom.xml"/></Relationships>

    The.rels file of the autocreated spreadsheet looks like this:

    <?xml version="1.0" encoding="utf-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml" Id="rId3" /><Relationship Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml" Id="rId2" /><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties" Target="docProps/custom.xml" Id="rId4" /><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="/xl/workbook2.xml" Id="rId1" /></Relationships>

    The two files in the "xl\ directory" is identical in contents but have different names.
    The file of the manually created spreadsheet is workbook.xml
    The file autocreated has the name workbook2.xml.

    Hope this helps in resoving this issue.


    Best Regards Peter Karlström Midrange AB, Sweden



    Friday, May 17, 2013 9:49 AM
  • Hi

    This is the second try with the same question. Precious try was on may 14, and I got no response inspite of the 48 hours responsetime.

    In one of my projects I've discovered a strange difference which affects further working with the Excel spreadsheet.

    First I create a new Excel spreadsheet from an existing template (XLTX) file using the following code:

        Public Function XLCreateExcelWbk(ByVal templatePath As String, ByVal workbookPath As String) As String
    
            Dim oldCulture As Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
            System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
            File.Copy(templatePath, workbookPath, True)
            File.SetAttributes(workbookPath, FileAttributes.Normal)
            Using wbok As SpreadsheetDocument = SpreadsheetDocument.Open(workbookPath, True)
                wbok.ChangeDocumentType(SpreadsheetDocumentType.Workbook)
            End Using
            System.Threading.Thread.CurrentThread.CurrentCulture = oldCulture
            Return workbookPath
    
        End Function

    When I compare the new file aith a manually created spreadsheet using Office 2010 the following difference is found in the file.

    Difference

    Is it something in my code or is this "by design"?

    And, most importand, how can I adjust the spreadsheet so that it contains the same XML-code that tha manually created file?

    Thanks in advance


    Best Regards Peter Karlström Midrange AB, Sweden


    Monday, June 24, 2013 7:48 AM
  • Hi Peter

    Have you checked the original file (xltx) whether the workbook in it is also named workbook2.xml? That that is the case would be the most logical explanation and the solution would be to manually open the Zip package, drag the workbook2.xml to the Desktop, rename it, drag it back in and then change the reference in the xl/_rels file.

    Or perhaps try opening it in Excel, then saving it again.

    By default, Excel will certainly name the xml contents of the Zip package as on the right. Something very odd must have been going on for the file to contain the name workbook2.xml, as on the left...


    Cindy Meister, VSTO/Word MVP, my blog

    Monday, June 24, 2013 9:33 AM
    Moderator
  • Hi Cindy

    Thanks for replying.

    Both the files in my file comparison above is created from the same xltx-file.

    I have also checked that the workbook name in the originall templats is called workbook.

    The first time workbook2 appears is when i "convert" it using the code in my post.

    Please let me know if you want the xltx-file for tests.


    Best Regards Peter Karlström Midrange AB, Sweden


    Monday, June 24, 2013 2:19 PM
  • Hi

    Thanks for your reply.

    Do you mean to Open Excel.exe?
    This is not possible using a WebService as this is all about.


    Best Regards Peter Karlström Midrange AB, Sweden

    Monday, June 24, 2013 2:27 PM
  • Hi Barcelona

    I seriously doubt that a background instance of Excel is used when manipulating a workbook using the Open XML SDK? The Open XML SDK will run on a system where Office is not installed.

    The workbook2.xml referred to in the original post has nothing to do with Excel naming a workbook in the Excel application. This is an XML part within a Zip package.


    Cindy Meister, VSTO/Word MVP, my blog

    Monday, June 24, 2013 3:46 PM
    Moderator
  • Could you post it on a service like Skydrive, please?

    Oh, and you might also test whether the internal name changes when you copy the file, or only after you've opened the file using System.IO.Packaging.


    Cindy Meister, VSTO/Word MVP, my blog


    Monday, June 24, 2013 3:47 PM
    Moderator
  • Hi Cindy

    Here is a link to SkyDrive with the Excel template.

    Link to template

    Also, open the file with Dim exlDocument As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) with AutoSave changed the date and time of the file but the name of workbook is the same.


    Best Regards Peter Karlström Midrange AB, Sweden

    Monday, June 24, 2013 5:26 PM
  • Hi Peter,

    Sorry for the late in reply.

    As mentioned by Brandon in Problems with creating a new presentation from potx file, this issue might have something to do with OpenXML SDK. 

    I've tried to involve some senior engineer into your newest thread. I believe you'll soon get replied.

    Sorry for any inconvenience.

    Best regards,


    Quist Zhang [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, June 25, 2013 6:47 AM
    Moderator
  • Hi Peter

    OK, I understand what's happening. The type of document is stored in the [Content_Types].xml file at the top level of the Zip package. If you were changing the file type manually, you could simply open it and change the entry

      <Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml" PartName="/xl/workbook.xml"/>

    to

      <Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" PartName="/xl/workbook.xml"/>

    Neither the Open XML SDK nor the System.IO.Packaging namespace on which it bases allows access to this top-level management file; the Open specification for the file format doesn't allow it. Instead, it's necessary to remove the existing part AND all its relationships and create a new part with the same relationships. The Open XML SDK first creates the new part, assigns the relationships, then deletes the old part (more efficient than going the other way around, deleting first). Since the file already has a workbook.xml the new part is named workbook2.xml.

    The simplest thing would probably be to use, create or license a Zip tool that can work directly with the files, as you're able to as an "end-user". I believe there's a free one available on CodePlex.

    The other way to go would be to write code to store a list of the relationships for the part, delete the part, then create a new part and restore the relationships. I don't have any code at-hand for that for the combination of English, Excel, VB.NET and Open XML SDK. What I would have is some text (incl. code) I wrote for a book that was never published in German, for Word, C# and System.IO.Packaging (precursor to the Open XML SDK, on which the Open XML SDK bases). If you think that would be of any help?


    Cindy Meister, VSTO/Word MVP, my blog

    Saturday, June 29, 2013 6:39 AM
    Moderator
  • Hi Cindy

    Thanks for your support.

    This looks very interesting, and I would be very glad if you could send me your unpublished information on this issue.

    I will test in in my environment and get back with the result here.

    I believe you can upload it to my Skydrive shared folder., or provide me with a link to one of your own.


    Best Regards Peter Karlström Midrange AB, Sweden

    Monday, July 1, 2013 7:33 AM
  • Hi Peter

    I didn't see any way to upload a file to the shared folder you provided so it's in a shared folder on my site (read only):

    http://sdrv.ms/1auTPuJ


    Cindy Meister, VSTO/Word MVP, my blog

    Monday, July 1, 2013 1:59 PM
    Moderator
  • Hi Cindy

    I think I have come up with a possible solution.

    This is a test on a Word document, and when I again compared the manually and the automated versions of the conversion (from dotx to docx) by unpack the files and manually check for differences, I found out that there is only 4 differences between the documents.

    Two files have the "wrong" document name, document2 instead of just document. I changed these in the unpacked folders.

    The other two files have wrong contents, pointing to document2 instead of document. These two files are \_rels\.rels and [Content_Types].xml in the package root. Now, the package root is not shown when unpacked with System.IO.Packaging, so I tested with one of the open source alternatives.

    I have tested this in code and when I reopen the "fixed" Word document it now looks as it's supposed to look.

    Is this pure luck or do you think I can use this?


    Best Regards Peter Karlström Midrange AB, Sweden

    Thursday, July 4, 2013 6:23 AM
  • Yes, this is basically what I said before, about finding a tool that can work with the files in the Zip package, directly, rather than having to live with the restrictions imposed by the spec and applied via System.IO.Packaging. It should work, as long as the Open XML SDK always uses the same pattern for naming internal files.

    Cindy Meister, VSTO/Word MVP, my blog

    Thursday, July 4, 2013 2:17 PM
    Moderator
  • Hi Cindy

    It seems I finally have a solution, which fixes the incorrect filenames and relations in the Office file.

    For others with the same problem, I post my sample code which is to be run with a copied template file which DocumentType is changed to document, spreadsheet or /presentation according to my code in the beginning of this post.

    I have used an open source library called Ionic.Zip on CodePlex (DotNetZip Homepage) to handle the zip package, since system.io.packaging doesn't support the [Content_type].xml file in the root of the package.

    In the code below, you can skip the WriteLogg-parts, since this is already implemented code in my project.

    targetTempPath is a temporary foöder which stores the temporary files from unpacking the office file.

    Friend Function WDSetXMLData(ByVal docPath As String, ByVal targetTempPath As String) As Boolean
    
            If Not targetTempPath.EndsWith("\") Then
                targetTempPath = targetTempPath & "\"
            End If
    
            Dim ZipToUnpack As String
            Dim oldName1 As String = "[Content_Types].xml"
            Dim oldName2 As String = "_rels/.rels"
            Dim oldName3 As String = "word/_rels/document2.xml.rels"
            Dim oldName4 As String = "word/document2.xml"
            Dim newName1 As String = targetTempPath & "[Content_Types].xml"
            Dim newName2 As String = targetTempPath & "_rels\.rels"
            Dim newName3 As String = targetTempPath & "word\_rels\document.xml.rels"
            Dim newName4 As String = targetTempPath & "word\document.xml"
            Dim newPath1 As String = ""
            Dim newPath2 As String = "_rels"
            Dim newPath3 As String = "word\_rels\"
            Dim newPath4 As String = "word\"
            Dim funcReturn As Boolean = True
    
            'Delete temp directory
            Try
                If My.Computer.FileSystem.DirectoryExists(targetTempPath) Then
                    My.Computer.FileSystem.DeleteDirectory(targetTempPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
                End If
            Catch ex As Exception
                WriteLogg("Fel vid borttag av temporär mapp " & targetTempPath & ". Fel: " & ex.Message, "WDSetContentType", logFile)
                Return False
                Exit Function
            End Try
    
            'Create new temp directory
            Try
                My.Computer.FileSystem.CreateDirectory(targetTempPath)
            Catch ex As Exception
                WriteLogg("Fel vid skapande av temporär mapp " & targetTempPath & ". Fel: " & ex.Message, "WDSetContentType", logFile)
                Return False
                Exit Function
            End Try
    
            'Make backup copy of original file
            Try
                FileCopy(docPath, targetTempPath & "tmpXMLDoc.docx")
                ZipToUnpack = targetTempPath & "tmpXMLDoc.docx"
            Catch ex As Exception
                WriteLogg("Fel vid säkerhetskopiering av dokument. Fel: " & ex.Message, "WDSetContentType", logFile)
                Return False
                Exit Function
            End Try
    
            'Unpack files
            Try
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName1 Then
                            e.Extract(targetTempPath, ExtractExistingFileAction.OverwriteSilently)
                        End If
                        If e.FileName = oldName2 Then
                            e.Extract(targetTempPath, ExtractExistingFileAction.OverwriteSilently)
                        End If
                        If e.FileName = oldName3 Then
                            e.Extract(targetTempPath, ExtractExistingFileAction.OverwriteSilently)
                        End If
                        If e.FileName = oldName4 Then
                            e.Extract(targetTempPath, ExtractExistingFileAction.OverwriteSilently)
                        End If
                    Next
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid uppackning av dokument. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Change file / [Content_Types].xml
            Try
                Dim infile As String = targetTempPath & "[Content_Types].xml"
                Dim strRead As StreamReader = New StreamReader(infile)
                Dim text As String = strRead.ReadToEnd()
    
                strRead.Close()
                text = text.Replace("/word/document2.xml", "/word/document.xml")
                Dim strWrite As New StreamWriter(infile, False)
    
                strWrite.Write(text)
                strWrite.Close()
            Catch ex As Exception
                WriteLogg("Fel vid ändring av fil [Content_Types].xml. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Change file / _rels/.rels
            Try
                Dim infile As String = targetTempPath & "_rels\.rels"
                Dim strRead As StreamReader = New StreamReader(infile)
                Dim text As String = strRead.ReadToEnd()
    
                strRead.Close()
                text = text.Replace("/word/document2.xml", "/word/document.xml")
                Dim strWrite As New StreamWriter(infile, False)
    
                strWrite.Write(text)
                strWrite.Close()
            Catch ex As Exception
                WriteLogg("Fel vid ändring av fil _rels/.rels. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Rename file / word/_rels/document2.xml.rels
            Try
                Dim tmpfName As String = oldName3.Replace("2", "")
                tmpfName = tmpfName.Replace("/", "\")
                Dim bPos As Int16 = InStrRev(tmpfName, "\")
                If bPos > 0 Then
                    tmpfName = tmpfName.Substring(bPos)
                End If
                Dim tmpoName As String = targetTempPath & oldName3.Replace("/", "\")
                My.Computer.FileSystem.RenameFile(tmpoName, tmpfName)
            Catch ex As Exception
                WriteLogg("Fel vid namnbyte av fil word/_rels/document2.xml.rels. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Rename file / word/document2.xml
            Try
                Dim tmpfName As String = oldName4.Replace("2", "")
                tmpfName = tmpfName.Replace("/", "\")
                Dim bPos As Int16 = InStrRev(tmpfName, "\")
                If bPos > 0 Then
                    tmpfName = tmpfName.Substring(bPos)
                End If
                Dim tmpoName As String = targetTempPath & oldName4.Replace("/", "\")
                My.Computer.FileSystem.RenameFile(tmpoName, tmpfName)
            Catch ex As Exception
                WriteLogg("Fel vid namnbyte av fil word/document2.xml. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Repack files - [Content_Types].xml
            Try
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName1 Then
                            'zip1.UpdateFile(newName1)
                            zip1.RemoveEntry(oldName1)
                            zip1.AddFile(newName1, "")
                            Exit For
                        End If
                    Next
                    zip1.Save(ZipToUnpack)
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid packning av xmlfil [Content_Types].xml. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Repack files - _rels/.rels
            Try
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName2 Then
                            'zip1.UpdateFile(newName2)
                            zip1.RemoveEntry(oldName2)
                            zip1.AddFile(newName2, newPath2)
                            Exit For
                        End If
                    Next
                    zip1.Save(ZipToUnpack)
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid packning av xmlfil _rels/.rels. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Repack files - word/_rels/document2.xml.rels
            Try
    
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName3 Then
                            zip1.RemoveEntry(oldName3)
                            zip1.AddFile(newName3, newPath3)
                            Exit For
                        End If
                    Next
                    zip1.Save(ZipToUnpack)
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid packning av xmlfil word/_rels/document.xml.rels. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Repack files - word/document.xml
            Try
                Using zip1 As Ionic.Zip.ZipFile = ZipFile.Read(ZipToUnpack)
                    Dim e As ZipEntry
                    For Each e In zip1
                        If e.FileName = oldName4 Then
                            zip1.RemoveEntry(oldName4)
                            zip1.AddFile(newName4, newPath4)
                            Exit For
                        End If
                    Next
                    zip1.Save()
                End Using
            Catch ex As Exception
                WriteLogg("Fel vid packning av word/document.xml. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Copy newfile to old
            Try
                FileCopy(targetTempPath & "tmpXMLDoc.docx", docPath)
            Catch ex As Exception
                WriteLogg("Fel vid kopiering av nytt dokument. Fel: " & ex.Message, "WDSetContentType", logFile)
                GoTo Rollback
            End Try
    
            'Delete temp directory
            Try
                My.Computer.FileSystem.DeleteDirectory(targetTempPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
            Catch ex As Exception
                WriteLogg("Fel vid borttag av temporär mapp " & targetTempPath & ". Fel: " & ex.Message, "WDSetContentType", logFile)
            End Try
    
            Return True
    Rollback:
    
            'Delete temp directory
            Try
                My.Computer.FileSystem.DeleteDirectory(targetTempPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
            Catch ex As Exception
                WriteLogg("Fel vid borttag av temporär mapp " & targetTempPath & ". Fel: " & ex.Message, "WDSetContentType", logFile)
            End Try
    
            Return False
    
        End Function
    

    This is all based on the fact that there (at the moment) is the same 4 differences in Word, Excel and Powerpoint.
    With no doubt they will change in coming releases from Microsoft, so this is something you have to watch out for in the future.

    Syntax for changes in Excel are for example xl/workbook2.xml, and for Powerpoint ppt/presentation2.xml


    Best Regards Peter Karlström Midrange AB, Sweden

    Friday, July 5, 2013 1:11 PM
  • I'm glad my suggestions led you to a workable solution :-)

    Cindy Meister, VSTO/Word MVP, my blog

    Friday, July 5, 2013 3:20 PM
    Moderator
  • Hi Cindy

    Yes, and again; Thank you.


    Best Regards Peter Karlström Midrange AB, Sweden

    Friday, July 5, 2013 3:21 PM