簡體   English   中英

在C#/ vb.net中將.doc轉換為.docx

[英]Convert .doc to .docx in c# / vb.net

Microsoft.Office.Interop.Word._Document mDocument = new Microsoft.Office.Interop.Word.Document();

*//This function will convert .doc to .docx
    Public Function FileSave(ByVal fileName As String, ByVal openPWD As String, ByVal savePWD As String)    
                mDocument.SaveAs2(fileName, WdSaveFormat.wdFormatXMLDocument, , openPWD, , savePWD)             
                End Function*

上面的函數已編寫為使用單詞互操作將.doc文件轉換為.docx。 文件創建成功,但是打開時文件內容丟失。

缺少某些東西或是否有其他方法可以在C#或Vb.net中將.doc轉換為.docx

您似乎正在內存中創建一個全新的Word文檔,然后將其另存為.DOCX,這就是輸出文件為空的原因。

// This line just creates a brand new empty document
Microsoft.Office.Interop.Word._Document mDocument = new Microsoft.Office.Interop.Word.Document();

您需要先打開現有文檔,然后打開所需的文件類型。

這樣的事情(我自己沒有像在Interop的機器上那樣測試過它)

Microsoft.Office.Interop.Word._Document mDocument = wordApp.Documents.Open(sourcepath);
mDocument.SaveAs(outputpath, WdSaveFormat.wdFormatXMLDocument);

在OP請求下,如何獲取Word實例

// Create Word object
Word._Application wordApp = null;

// Try and get an existing instance
try
{
    wordApp = (Word._Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
}
catch { /* Ignore error */ }

// Check if we got an instance, if not then create one
if (wordApp == null)
{
    wordApp = new Microsoft.Office.Interop.Word.Application();
}

//Now you can use wordApp
... wordApp.Documents.Open(...);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM