word 文档的读写类

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using System.Drawing.Imaging;

namespace OpenWord
{
    public partial class Form1 : Form
    {
       
        public Form1()
        {
            InitializeComponent();
        }
        //object filename = @"d:\新建 Microsoft Word 文档.docx";//文件名
      //  object filename = @"d:\田原-法硕(法学)-对外经济贸易大学.doc";OK
        //王仲磊个人简历
        //object filename = @"d:\王仲磊个人简历.doc";//OK
        object filename = @"d:\个人简历马龙.doc";
        Microsoft.Office.Interop.Word.Application a = new Microsoft.Office.Interop.Word.Application();
        Document b = null;
        private void button1_Click(object sender, EventArgs e)
        {
           
           //建立一个Word程序对像
            object Nothing = System.Reflection.Missing.Value;//空值
            b = a.Documents.Open(ref filename,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);//建立一个Word文档对像            
            a.Visible = false;
            //其实这步就是执行了这个宏
            //a.Selection.InlineShapes.AddPicture(@"D:\图片\卡通\fc4054667543fb0eaa184c59.jpg", ref Nothing, ref Nothing, ref Nothing);
            Selection.InlineShapes.AddPicture FileName:= "C:\Documents and Settings\Administrator\桌面\2003121512223366481.bmp", LinkToFile:=False, SaveWithDocument:=True   End Sub    b.Save();//保存
            //a.ActiveDocument.Words.First.InsertBefore("sdfsdfsdfsdf");
            //a.ActiveDocument.Words.Last.InsertAfter("jieweejieejiejie");
            //b.Close(ref Nothing,ref Nothing,ref Nothing);//关闭Word文档
            //a.Quit(ref Nothing,ref Nothing,ref Nothing);//退出Word程序
            MessageBox.Show("成功打开word文档");
           
       
 
        }

        private void button2_Click(object sender, EventArgs e)
        {
        //   int n= getParCount();
           object strig= ReadPar();
           MessageBox.Show(strig.ToString());
           GetImageFromWord();
        
           CloseFile();
           quit();
        }
        public void openFile()
        {
            try
            {
              if(a.Documents.Count>0)
              {
                  if(MessageBox.Show("已经打开一个word文档,你想关闭重新打开该文档吗?","提示",MessageBoxButtons.YesNo)==DialogResult.Yes)
                  {
                      object unknow=Type.Missing;
                      b=a.ActiveDocument;
                      if(MessageBox.Show("是否保存","提示",MessageBoxButtons.YesNo)==DialogResult.Yes)
                      {
                          a.ActiveDocument.Save();
                      }
                      a.ActiveDocument.Close(ref unknow,ref unknow,ref unknow);
                      a.Visible=false;
                  }
                  else
                  {
                      return;
                  }
              }
            }
            catch (Exception e)
            {
                a = new Microsoft.Office.Interop.Word.Application();

            }
            //try
            //{

            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }
        /// <summary>
        /// 读取word中的文本内容
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public object ReadPar()
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                //读取word中的一段(一行)
                for (int index = 1; index <= b.Paragraphs.Count; index++)
                {
                    string tmp = b.Paragraphs[index].Range.Text.Trim();
                    sb.Append(tmp);
                    sb.Append("\n");
                }
               // string tmp = b.Paragraphs[i].Range.Text.Trim();
                //读取一句,以句号结尾
               // string tmp = b.Sentences[i].Text.Trim();

                return sb;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return null;
            }

        }
        public int getParCount()
        {
            int nCount = b.Paragraphs.Count;
            return nCount;
        }
        /// <summary>
        /// 关闭word文档
        /// </summary>

        public void CloseFile()
        {
            try
            {
                object unKnow = Type.Missing;
                object saveoption = Microsoft.Office.Interop.Word.WdSaveOptions.wdPromptToSaveChanges;
                a.ActiveDocument.Close(ref saveoption, ref unKnow, ref unKnow);

            }
            catch (Exception ex)
            {
                MessageBox.Show("关闭word文档时出现异常"+ex.Message);
            }
        }
        /// <summary>
        /// 退出word程序
        /// </summary>
        public void quit()
        {
            try
            {
                object unknow = Type.Missing;
                object saveOp = Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges;
                a.Quit(ref saveOp, ref unknow, ref unknow);
            }
            catch (Exception p)
            {
                MessageBox.Show("退出word程序时出现异常 "+p.Message);
            }
        }
        //word中替换.
        public void replaceChar()
        {
            object replaceType = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
            object missining = Type.Missing;
            a.Selection.Find.ClearFormatting();
            a.Selection.Find.Text = "^1";
            a.Selection.Find.Replacement.ClearFormatting();
            a.Selection.Find.Replacement.Text = "^P";

            a.Selection.Find.Execute(ref missining,ref missining,ref missining,ref missining,ref missining,
                ref missining,ref missining,ref missining,ref missining,ref missining,ref replaceType,ref missining,ref missining,ref missining,ref missining);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            GetTableInfo();
            CloseFile();
            quit();
        }
        public void  GetTableInfo()
        {
            for (int tableIndex = 1; tableIndex <= b.Tables.Count; tableIndex++)
            {
                Microsoft.Office.Interop.Word.Table nowTable = b.Tables[tableIndex];
                string tableMessage = String.Format("第{0}/{1}个表:\n",tableIndex,b.Tables.Count);
                for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
                {
                    if (rowPos != 2)
                    {
                        for (int columPos = 1; columPos <= nowTable.Columns.Count; columPos++)
                        {
                            tableMessage += nowTable.Cell(rowPos, columPos).Range.Text;
                            tableMessage = tableMessage.Remove(tableMessage.Length - 2, 2);//remove \r\a
                            tableMessage += "\t";

                        }
                        tableMessage += "\n";
                    }
                    else
                    {
                        GetImageFromWord();
                    }
                }
                FillTableCell(nowTable.Cell(2, nowTable.Columns.Count).Range);
                MessageBox.Show(tableMessage);
            
 
            }
         }
        /// <summary>
        /// 从word中获取图片并将图片保存到文件中
        /// </summary>
        public void GetImageFromWord()
        {
            List<InlineShape> allShape = new List<InlineShape>();    //用InlineShape类型保存图片
            List<Image> allImage = new List<Image>();          //用Image类型保存图片
            //获取文档中所有的嵌入式图像
            foreach (Microsoft.Office.Interop.Word.InlineShape ins in b.InlineShapes)
            {
                MessageBox.Show("获取图片");
               if (ins.Type == WdInlineShapeType.wdInlineShapePicture)
              //  if(ins.Type==WdInlineShapeType.wdInlineShapeLinkedPicture )
                {
                    allShape.Add(ins);

                }

            }
            Microsoft.Office.Interop.Word.Selection sel;
            System.Drawing.Image returnImage = null;
            foreach (InlineShape ins in allShape)
            {
                ins.Select();
                sel = a.Selection;

                if (sel.Type == WdSelectionType.wdSelectionInlineShape)
                {
                    sel.CopyAsPicture();
                    if (Clipboard.ContainsImage())
                    {
                        returnImage = Clipboard.GetImage();
                        allImage.Add(returnImage);
                    }

                }
            }
            //清空剪切板
            Clipboard.Clear();
            int i = 0;
            foreach (Image im in allImage)
            {
                im.Save("D:\\图片\\" + i.ToString() + ".jpg", ImageFormat.Jpeg);
                i++;
            }
            MessageBox.Show("word中的图像成功保存到文件中");
        }
       /// <summary>
       /// 用一个图像文件去填充word中的表格的某一列,或是在指定的区域插入一张图片
       /// </summary>
       /// <param name="objRang"></param>
        public void FillTableCell(object objRang)
        {

            string fileName = "D:\\图片0.jpg ";     //要插入的图片
            Object oMissed = objRang; //插入的位置,替换第二段内容
            Object oLinkToFile = false;     //缺省
            Object oSaveWithDocument = true;//缺省
            b.InlineShapes.AddPicture(fileName, ref     oLinkToFile, ref     oSaveWithDocument, ref     oMissed);     //doc为活动文档的名称,即正在操作的文档

        }
      
        private void button4_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Document doc = new Document();

            object oMissing = System.Reflection.Missing.Value;//这个是什么东西,我始终没搞明白-_-
            //打开模板文档,并指定doc的文档类型
            object objTemplate = @"D:\Doc1.dot";
            object objTrue = Type.Missing;
            object objFalse = Type.Missing;
            object objDocType = WdDocumentType.wdTypeDocument;
            doc = (Document)a.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);
            //获取模板中所有的书签
            Bookmarks odf = doc.Bookmarks;
            if (doc.Bookmarks.Exists("年龄"))
            {
                MessageBox.Show("书签存在");
            }
            object objIndex = "年龄";
            doc.Bookmarks[objIndex].Range.Text = "1111111";
            object filename = @"d:\" +  "1233.doc";
            object miss = System.Reflection.Missing.Value;
            doc.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            object missingValue = Type.Missing;
            object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
            doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
            doc = null;
            CloseFile();
            quit();
            MessageBox.Show("成功修改某个标签处的值");

        
          //  Type docsType = b.GetType();
          //    Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open",
          //System.Reflection.BindingFlags.InvokeMethod, null, b, new Object[]{ filename, true, true });

          //    Type docType = doc.GetType();

        }


    }
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值