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); 
        }
   
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值