sqtsqt 发表于 2015-9-14 09:55:45

VSTO 得到Office文档的选中内容(Word、Excel、PPT、Outlook)

原文:VSTO 得到Office文档的选中内容(Word、Excel、PPT、Outlook)
    目的:得到在Word、Excel、PPT、Outlook中选中的一段内容。
  Word:
  private string GetSelectCont()
      {
            string w = "";
            Word.Selection sec = appWord.Selection;
            Word.Words wds = sec.Words;            
            w = wds.Application.Selection.Text;
            return w.Trim();
      }
  Outlook:
  private string GetSelectCont(Outlook.Inspector Inspector)
       {
            string w = "";
  Word.Document document = Inspector.WordEditor;            
            w = document.Application.Selection.Words.Application.Selection.Text;            
            return w.Trim();
       }
  注:无法得到标题等之类的选中内容。
  PPT:
  private string GetSelectCont()
      {
            string w = "";
   PowerPoint.Selection sec = appPPT.ActiveWindow.Selection;
            string word = sec.TextRange.Text;
            return word.Trim();
      }
  Excel:
  private string GetSelectCont()
      {
            string w = "";
            object[,] result;
            object res1;
            string res2;
            Excel.Workbook wbook = Globals.ThisAddIn.Application.ActiveWorkbook;//当前活动workbook
            Excel.Worksheet wsheet = (Excel.Worksheet)wbook.ActiveSheet;          //当前活动sheet
            Excel.Range range = (Excel.Range)wsheet.Application.Selection;      //当前选中的cells
  int count = range.Count;
            res1 = (object)range.Value2;
            //如果选中多个单元格
             if (count > 1)
             {
               int row_count = range.Rows.Count;
               int col_count = range.Columns.Count;
               result = (object[,])res1;
               for (int i = 1; i <= row_count; i++)
               {
                     for (int j = 1; j <= col_count; j++)
                     {
                         if (result != null)
                         {
                           w += (string)result + " ";
                         }
                     }
               }
             }
             else {
               //如果选中单个
               if (res1 == null)
               {
                     w = "";
               }
               else {                  
                     res2 = res1.ToString();
                     w = res2;
               }
             }
            return w.Trim();
      }
  注:Excel比较复杂,这只能得到选中单个或多个单元格的内容,却不能得到某个单元格中mark起来的内容,正在查找解决办法。。。
  
页: [1]
查看完整版本: VSTO 得到Office文档的选中内容(Word、Excel、PPT、Outlook)