简体   繁体   English

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

[英]How can I programmatically delete a line from a Word document using c#?

I have some code to find and replace fields in a word document with values from a dataset. 我有一些代码来查找和替换word文档中的字段与数据集中的值。

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. 在某些情况下, stringValueFromDataSet为空,除了不插入任何内容外,我想实际删除当前行。

Any idea how I can do this? 知道我怎么能这样做吗?

好吧,这最终是非常容易的。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C#中使用CreateObject打开Word文档? - How can I open a word document by using CreateObject in C#? 如何从C#获取Word文档的文件名? - How can I get the filename of a Word document from C#? 如何使用vs 2010,C#以编程方式在Word 2007文档中插入或编辑饼图? - How do I programmatically insert, or edit, a pie chart in a Word 2007 document, using vs 2010, c#? 如何在C#中使用OpenXml从Word文档中删除两个书签中的数据或表 - How to delete data or table within two bookmarks from word document using OpenXml in C# 如何使用C#以编程方式将Microsoft Word注释转换为书签? - How can I programmatically convert Microsoft Word comments to bookmarks using C#? C#VSTO如何从Word文档返回交叉引用 - C# VSTO How can can I return the cross references from the Word document 使用C#以编程方式编辑大型Word文档 - Programmatically edit a large word document using C# 使用 c# 以编程方式设置 Word 文档表格单元格边距 - Setting word document table cell margin programmatically using c# 如何使用DocX在Word文档中插入换行符? - How can I insert a line break in a Word document using DocX? 如何使用C#在Office 365 / OneDrive for Business中创建Word文档 - How can I create a Word document in office 365 / 'OneDrive for Business' using c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM