2011-10-18 79 views
2

我一直在使用以下代碼來編寫word文件,但無法存儲word文件。有什麼方法可以使用C#存儲單詞文件嗎?如何使用C保存doc文件

object oMissing = System.Reflection.Missing.Value; 
       object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ 
       //Start Word and create a new document. 
       Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application(); 

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

      oWord.Visible = true; 

      oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 

      //Insert a paragraph at the beginning of the document. 
      Microsoft.Office.Interop.Word.Paragraph oPara1; 

      oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); 
      oPara1.Range.Text = "Heading 1"; 
      oPara1.Range.Font.Bold = 1; 
      oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. 
+1

並且調用oDoc上的Save方法不起作用? http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word._document.save.aspx另請參閱此處:http://msdn.microsoft.com/en-us/library/microsoft .office.interop.word._document_members.aspx – Icarus

+2

或SaveAs:http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word._document.saveas.aspx –

回答

8

您應該只能使用SaveAs。

oDoc.SaveAs("MyFile.doc", ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 

如果您使用的是.NET 4.0,則不需要oMissings。

小號

+1

+1;打敗了我。但是,如果他們不使用C#4,那麼fileName必須通過引用傳遞。 – vcsjones

0

試試這個:

var FileName = 'file name with path' 

    oWord.ActiveDocument.SaveAs(ref FileName, ref missing, 
         ref missing, ref missing, ref missing, 
         ref missing, ref missing, ref missing, 
         ref missing, ref missing, ref missing, 
         ref missing, ref missing, ref missing, 
         ref missing, ref missing); 
    oDoc.Close(ref missing, ref missing, ref missing); 
4

我剛剛創建使用.NET 4和C#Microsoft Word對象庫一個新的控制檯應用程序,引用,粘貼你的代碼,並刪除了所有那些ref missing與。 NET 4和可選參數不再需要,這裏的最終代碼真的很像charme:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

using Microsoft.Office.Interop.Word; 

namespace ConsoleApplication5 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Microsoft.Office.Interop.Word._Application oWord = new Application(); 

      oWord.Visible = true; 

      var oDoc = oWord.Documents.Add(); 

      //Insert a paragraph at the beginning of the document. 
      var paragraph1 = oDoc.Content.Paragraphs.Add(); 

      paragraph1.Range.Text = "Heading 1"; 
      paragraph1.Range.Font.Bold = 1; 
      paragraph1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. 

      oDoc.SaveAs2(@"C:\Temp\TestDocumentWith1Paragraph.docx"); 

      oWord.Quit(); 
     } 
    } 
}