简体   繁体   中英

VB .NET automation, Document.SaveAs corrupting Word Document

Just to start I try to summarize what I want to do:

My vb .net app done in vs2019 simply automates and fills a word template, it should at the end save it in a folder provided by a text box saved in the variable URL.

Everything is fine and dandy but if I try to open the word docx I get this:

在此处输入图片说明单词错误 .

Also if I save using the saveAs from word itself,manually, the file isn't corrupted anymore. And there is difference in size between the files that are pretty much the same:

在此处输入图片说明word文档差异1 .

在此处输入图片说明word文档差异2 .

在此处输入图片说明word文档区别3 .

SO, the file "Adresa OCPI2" is a corrupted file "Adresa OCPI" that was simply renamed. "Adresa OCPI" was saved manually.

WPS office can for some reason open the corrupted file, but I had to remove the app because it wasn't good for automation.

Using Word 2007, and on another computer with 2019 it has the same issue :(. Technically if the references were bad I wouldn't be able to get to the save point :/ but its debatable.

Tried closing at the end with ("oDoc.Close() oWord.Quit() and Me. Close()") but no difference

Imports Microsoft.Office.Interop
Imports Word = Microsoft.Office.Interop.Word
Dim oWord As Word.Application
                Dim oDoc As Word.Document
                Dim URL As String 
URL = TextBox9.Text
oWord = CreateObject("Word.Application")
                oWord.Visible = True
oDoc = oWord.Documents.Open(URL & "\AdresaOCPITemplate.dotx")
oDoc.Activate()

...

oDoc.SaveAs(URL & "\Adresa OCPI.docx")

I simply don't want to manually save stuff, and sorry if it looks to simple :/ Edit 1, unzip docx, found xml diff that appeared also in details.

在此处输入图片说明

在此处输入图片说明

Edit 2 out of curiosity I tried this combination of code at the end

oDoc.Close()
oDoc = oWord.Documents.Open(URL & "\Adresa OCPI.docx")

and got:
"Word encountered an error processing the XML file Adresa OCPI" no code errors, this was received during debug

Is it by any chance the fact that the dotx format is broken and I should use docx as template instead????

Edit 3 Head hurts, docx has no issue, but I wanted extra safety with dotx so the files don't get accidentally overridden or modified. So technically I found a work around but I do wish to use dotx in the end, will leave this question open for our NA friends, maybe they wake up, will close it soon.

Edit 4:

How do I edit an existing MS Word template (.dotx) with VB.NET?

Mods please don't close my question yet...

The Open opens the template for editing, then you save it as docx while internally it's still dotx. You should use Documents.Add instead of Documents.Open. – GSerg from comments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM