如何用C#反转ms-word文档中的所有单词?

时间:2013-02-25 19:02:38

标签: c# vb.net ms-word ms-office office-interop

文档格式不应更改。除了单词顺序之外没有任何改变。

文件:

Word1 word2 word3 word2... -- END OF LINE OR PARAGRAPH
Word5 word1 word5 word4.....

倒车后应该如下

1droW 2drow 3drow 2drow... -- END OF LINE OR PARAGHRAPH
5droW 1drow 5drow 4drow..... 

我已经有了这个代码逐个完成单词,但我不知道如何更改而不会丢失格式。

string RT = "";


Word.Application wordObject = new Word.Application();
wordObject.Visible = false;

Word.Document docs = wordObject.Documents.Open(@"D:\ELAHE (J)\a.docx");

String strLine;
bool bolEOF = false;

docs.Characters[1].Select();

int index = 0;
do {

    object unit = Word.WdUnits.wdWord;
    object count = 1;
    wordObject.Selection.MoveEnd(ref unit, ref count);

    wordObject.Selection.InsertBefore("‭");
    strLine = wordObject.Selection.Text;
    RT += ++index + " - " + strLine + "\r\n"; 


    object direction = Word.WdCollapseDirection.wdCollapseEnd;
    wordObject.Selection.Collapse(ref direction);

    if (cnt++ > 100) break;

    if (wordObject.Selection.Bookmarks.Exists(@"\EndOfDoc")) bolEOF = true;
} while (!bolEOF);

docs.Close();
wordObject.Quit();
docs = null;
wordObject = null;

1 个答案:

答案 0 :(得分:1)

刚刚创建了一个如何完成此操作的示例(C#5.0,Word Interop v.15(Office 2013))。代码遍历每个段落并反转段落中的每个单词。该代码包括检查行尾符号(\r)以确保不反转这些符号。

我不是100%确定\r是Word使用的唯一行尾符号,因此如果您遇到其他类型,例如\r\n或类似的东西,它应该是直截了当地包括对这些的检查。

var wordApplication = new Application() { Visible = true };
var myDocument = wordApplication.Documents.Open(@"C:\Users\...\my.docx");

for (var i = 1; i <= myDocument.Paragraphs.Count; i++)
{
    var paragraph = myDocument.Paragraphs[i];
    var words = paragraph.Range.Words.Cast<Range>().Select(r => r.Text).ToList();

    // Empty paragraph -> continue
    if(words.Count == 1 && words[0] == "\r")
        continue;

    for (var j = 0; j < words.Count; j++)
    {
        var word = words[j];

        // Should not be reversed
        if(word == "\r")
            continue;

        var reversed = new string(word.Trim().Reverse().ToArray());

        words[j] = (word.EndsWith(" ")) ? reversed + " " : reversed;
    }

    paragraph.Range.Text = string.Join("", words);
}