0

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

文档 :

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;
4

1 回答 1

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);
}
于 2013-02-26T22:33:41.313 回答