C#进行Word文件的互操作

来源:互联网 发布:西安java 编辑:程序博客网 时间:2024/06/16 15:37
         近日用到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); 
        }
   
原创粉丝点击