如何使用 C# 以编程方式从 Word 文档中删除一行?

发布于 2024-08-13 22:22:33 字数 354 浏览 2 评论 0原文

我有一些代码可以查找 Word 文档中的字段并将其替换为数据集中的值。

Word.Document oWordDoc = new Word.Document();  
foreach (Word.Field mergeField in oWordDoc.Fields)  
{  
   mergeField.Select();  
   oWord.Selection.TypeText( stringValueFromDataSet );  
}

在某些情况下,stringValueFromDataSet 为空,除了不插入任何内容之外,我还想实际删除当前行。

知道我该怎么做吗?

I have some code to find and replace fields in a word document with values from a dataset.

Word.Document oWordDoc = new Word.Document();  
foreach (Word.Field mergeField in oWordDoc.Fields)  
{  
   mergeField.Select();  
   oWord.Selection.TypeText( stringValueFromDataSet );  
}

In some cases stringValueFromDataSet is empty, and in addition to inserting nothing, I want to actually delete the current line.

Any idea how I can do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

⊕婉儿 2024-08-20 22:22:33

好吧,这最终变得非常简单。

oWord.Selection.TypeBackspace();//删除字段
oWord.Selection.TypeBackspace();//删除该行

OK this was ridiculously easy in the end.

oWord.Selection.TypeBackspace();//remove the field
oWord.Selection.TypeBackspace();//remove the line

孤城病女 2024-08-20 22:22:33

显然,您的答案适用于您的情况。然而,在一般情况下(其中
不能使用退格键删除整行)可以使用以下内容:

    private static object missing = System.Reflection.Missing.Value;

    /// <summary>
    /// Deletes the line in which there is a selection.
    /// </summary>
    /// <param name="application">Instance of Application object.</param>
    private void DeleteCurrentSelectionLine(_Application application)
    {
        object wdLine = WdUnits.wdLine;
        object wdCharacter = WdUnits.wdCharacter;
        object wdExtend = WdMovementType.wdExtend;
        object count = 1;

        Selection selection = application.Selection;
        selection.HomeKey(ref wdLine, ref missing);
        selection.MoveDown(ref wdLine, ref count, ref wdExtend);
        selection.Delete(ref wdCharacter, ref missing);
    }

Obviously, your answer works in your case. However in the general case (where the
entire line cannot be removed using a backspace) the following can be used:

    private static object missing = System.Reflection.Missing.Value;

    /// <summary>
    /// Deletes the line in which there is a selection.
    /// </summary>
    /// <param name="application">Instance of Application object.</param>
    private void DeleteCurrentSelectionLine(_Application application)
    {
        object wdLine = WdUnits.wdLine;
        object wdCharacter = WdUnits.wdCharacter;
        object wdExtend = WdMovementType.wdExtend;
        object count = 1;

        Selection selection = application.Selection;
        selection.HomeKey(ref wdLine, ref missing);
        selection.MoveDown(ref wdLine, ref count, ref wdExtend);
        selection.Delete(ref wdCharacter, ref missing);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文