如何 select 仅在 Word table 单元格中输入文本

How to select text only in a Word table cell

我正在尝试使用 C# 仅 select 单词 table 单元格内的文本,以便我可以右键单击 selected 文本并分配超链接。问题是我尝试的所有内容 select 都是整个单元格,而不是单独的文本。因为单元格是 selected,右键单击上下文菜单不提供超链接选项。

我在 SO 的其他地方发现了一些有前途的 VBA 代码,我正在尝试使用 C# 对其进行建模。但没有任何效果。无论我做什么,整个单元格总是 selected。

我将光标放在单元格中,运行 下面代码的变体。我做错了什么?

// 
// VBA to select characters 4 through 9 in a cell
//itable.Cell(1,2).Range.Characters(4).Select
//Selection.MoveEnd wdCharacter, 5

// C#
var cell = sel.Range.Cells[1];
var text = cell.Range.Text; // to see it in the debugger
cell.Range.Start = cell.Range.Text[0];
cell.Range.End = cell.Range.Text.Length - 3;
cell.Range.Select();

// OR model the VBA code above, but this doesn’t work either
// use -1 for trim \r and -1 for 0-based 
//var moveLength = cell.Range.Text.Length - 2;
//sel.MoveEnd(WdUnits.wdCharacter, moveLength);

以下代码将展示如何仅 select table 单元格(在 Word 文档中)中的文本而不是整个单元格。作为奖励,在完整代码中,我包含了显示如何以编程方式将 table 单元格中的文本更改为超链接的代码。但是,由于这不是 OP 的一部分,因此被注释掉了。

添加以下 using 语句:

using Word = Microsoft.Office.Interop.Word;

代码片段:

private Word.Application _wordApp = new Word.Application();
private Word.Document _doc = null;

               ...

public void HighlightCellText(string filename, int tableNum, int row, int col)
{
    object oMissing = System.Reflection.Missing.Value;

    //set Word visibility
    _wordApp.Visible = true;

    //open Word document
    _doc = _wordApp.Documents.Open(filename, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, isVisible, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
    _doc.Activate();

    //desired table cell
    Word.Cell cell = _doc.Tables[tableNum].Cell(row, col);

    Word.Range rng = cell.Range;
    rng.MoveEnd(Microsoft.Office.Interop.Word.WdUnits.wdCharacter, -1);
    rng.Select();

               ...

}

HelperWord.cs(完整代码)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Office = Microsoft.Office.Interop;
using Word = Microsoft.Office.Interop.Word;
using System.IO;

namespace WordInteropHighlightCellText
{
    public class HelperWord : IDisposable
    {
        //create new instance
        private Word.Application _wordApp = new Word.Application();
        private Word.Document _doc = null;

        public string Filename { get; set; } = string.Empty;
        public void Dispose()
        {
            if (_doc != null && !String.IsNullOrEmpty(Filename))
            {
               //save document
                _doc.SaveAs2(Filename, Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdWord2013);
                _doc = null;
            }

            if (_wordApp != null)
            {
                //close Word
                object oFalse = false;
                _wordApp.Quit(ref oFalse, ref oFalse, ref oFalse);

                //release all resources
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_wordApp);

                _wordApp = null;

            }
        }

        public void HighlightCellText(string filename, int tableNum, int row, int col)
        {

            string errMsg = string.Empty;
            bool isVisible = true;
            object oMissing = System.Reflection.Missing.Value;
            object oEndOfDoc = "\endofdoc"; /* \endofdoc is a predefined bookmark */

            if (!File.Exists(filename))
            {
                errMsg = String.Format("Filename '{0}' not found.", filename);
                throw new Exception(errMsg);
            }

            //suppress displaying alerts (such as prompting to overwrite existing file)
            _wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

            //set Word visibility
            _wordApp.Visible = isVisible;

            //if writing/updating a large amount of data
            //disable screen updating by setting value to false
            //for better performance.
            //re-enable when done writing/updating data, if desired
            //_wordApp.ScreenUpdating = false;

            //open Word document
            _doc = _wordApp.Documents.Open(filename, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, isVisible, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
            _doc.Activate();

            //desired table cell
            Word.Cell cell = _doc.Tables[tableNum].Cell(row, col);

            Word.Range rng = cell.Range;
            rng.MoveEnd(Microsoft.Office.Interop.Word.WdUnits.wdCharacter, -1);
            rng.Select();

            //the following code will make the text in the table cell a hyperlink with the specified link address
            //convert text to hyperlink
            //object linkAddress = "https:\www.microsoft.com";
            //object oRng = cell.Range;
            //cell.Range.Hyperlinks.Add(oRng, ref linkAddress, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //works


            if (!_wordApp.ScreenUpdating)
            {
                //in case screen updating was previously disabled, 
                //enable screen updating by setting value to true
                _wordApp.ScreenUpdating = true;

                //refresh screen
                //_wordApp.ScreenRefresh();
            }

            if (!String.IsNullOrEmpty(filename))
            {
                try
                {
                    //save the document
                    //_doc.SaveAs(filename, 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);
                    _doc.SaveAs2(filename, Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdWord2013);

                }//try
                catch (Exception ex)
                {
                    errMsg = "Error: WordWriteDocument - " + ex.Message;
                    System.Diagnostics.Debug.WriteLine(errMsg);

                    if (ex.Message.StartsWith("Cannot access read-only document"))
                    {
                        System.Windows.Forms.MessageBox.Show(ex.Message + "Please close the Word document, before trying again.", "Error - Saving", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                }
            }
        }
    
    }
}

资源: