[英]How to reverse all words in a ms-word document with C#?
The document formatting should not change. 文档格式不应更改。 Nothing change other than words order. 除了单词顺序没有其他变化。
Document : 文件:
Word1 word2 word3 word2... -- END OF LINE OR PARAGRAPH
Word5 word1 word5 word4.....
After reversing should be like following 反转后应如下
1droW 2drow 3drow 2drow... -- END OF LINE OR PARAGHRAPH
5droW 1drow 5drow 4drow.....
Already I have this code to go through words one by one but I don't have any idea how to change without missing formatting. 我已经有这段代码可以逐字逐句地进行操作了,但是我不知道如何更改而不丢失格式。
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;
Just created a sample of how this can be done (C# 5.0, Word Interop v. 15 (Office 2013)). 刚刚创建了一个有关如何完成此操作的示例(C#5.0,Word Interop v。15(Office 2013))。 The code loops through each paragraph and reverses each word in a paragraph. 该代码循环遍历每个段落,并反转一个段落中的每个单词。 The code includes a check for end-of-line symbols ( \\r
) to make sure that these are not reversed. 该代码包括对行尾符号( \\r
)的检查,以确保这些符号不会被颠倒。
I'm not 100% sure that \\r
is the only end-of-line symbol used by Word, so if you encounter other kinds, eg \\r\\n
or something similar, it should be rather straight forward to include checks for these as well. 我不是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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.