C#進行Word文件的互操作

         近日用到word文件的讀取,先摘錄最基本的從word文件讀取文本和往word文件中加入文本的操作。具體關於文檔格式的讀取還在學習中。
        using Microsoft.Office.Interop.Word;
        
using System.IO;
      
//操作Word文件

        
//新建一個word文件,然後追加內容
        Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
        
object path = @"D:RogerWithLogWORDNewTest.doc";
        Document myWordDoc;
        
if (File.Exists(path.ToString()))
        
{
            File.Delete(path.ToString());
        }

        Object Nothing 
= System.Reflection.Missing.Value;
        myWordDoc 
= myWordApp.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);

        
string con = "This message will be added to the end of the passage Another Line?";
        myWordDoc.Paragraphs.Last.Range.Text 
= con;

        
//將WordDoc文檔對象的內容保存爲DOC文檔 
        myWordDoc.SaveAs(ref path, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
        
//關閉WordDoc文檔對象 
        myWordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
        
//關閉WordApp組件對象
        myWordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
        

        
//打開文件讀取內容
        Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
        
object path = @"D:RogerWithLogWORDNewTest.doc";
        Document myWordDoc;
        
if (File.Exists(path.ToString()))
        
{
            Object oMissing 
= System.Reflection.Missing.Value;
            myWordDoc 
= myWordApp.Documents.Open(ref path, 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);

            myWordDoc.Save();
            TextBox1.Text 
= myWordDoc.Content.Text;
            myWordDoc.Close(
ref oMissing, ref oMissing, ref oMissing);
            myWordApp.Quit(
ref oMissing, ref oMissing, ref oMissing); 
        }
   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章