【问题标题】:How to select text only in a Word table cell如何仅在 Word 表格单元格中选择文本
【发布时间】:2021-07-09 01:14:59
【问题描述】:

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

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

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

// https://stackoverflow.com/questions/33946827/ms-word-select-text-inside-a-table-cell
// 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);

【问题讨论】:

    标签: c# ms-word


    【解决方案1】:

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

    添加以下 using 语句:

    using Word = Microsoft.Office.Interop.Word;
    

    代码 sn-p

    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);
                        }
                    }
                }
            }
        
        }
    }
    

    资源

    【讨论】:

    • 多么棒的答案。你让它看起来很容易。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 2017-04-03
    • 2011-10-20
    相关资源
    最近更新 更多