【链接中的代码】(好像是他们项目用的,不通用):
internal static void InsertXML_W14_mimic_W11(this Word.Range range, string text) { // W11: // 1. Last paragraph is inserted with no ending '\r' and target paragraph formatting is retained. // 2. Any preceding paragraphs are inserted with ending '\r' and source paragraph formatting is used. // W14: // All paragraphs are inserted with ending '\r' and source paragraph formatting is used. // With W14 range stopped including the inserted text after InsertXML is called. // The range of range is now a point before the inserted text. // // We want to keep W11 behaviour. // range.End would move with rng if range includes end of header/footer or body Word.Range max_range = range.Duplicate; max_range.MoveEnd(Word.WdUnits.wdStory, 1); // End is moved as far as it goes (be it in header/footer or body) if (range.End == max_range.End) range.End--; Word.Range rng = range.Duplicate; rng.InsertAfter("\r#"); // Needed to work out end of range after range.InsertXML() // Get hold of target paragraph format. // Ie last paragraph in target range or following paragraph if target range ends with '\r'. Word.ParagraphFormat pf = rng.Paragraphs.Last.Format.Duplicate; range.InsertXML(text); // range.End is now equal range.Start (W14 bug, in W11 range.End would be after inserted text). // rng is now range.Start + inserted text + "\r" + "#". // Due to trailing \r paragraph format for last inserted paragraph is from source instead of target (as it would be with W11). // Work out if last paragraph before "#" is not empty (ie not '\r'). // If so we will apply target paragraph markup to "last" paragraph. bool use_target_p_markup_for_last_para = rng.Paragraphs.Count > 1 && (rng.Paragraphs[rng.Paragraphs.Count - 1].Range.Text != "\r" || rng.Paragraphs[rng.Paragraphs.Count - 1].Range.Fields.Count > 0); // Remove "\r#" and set range as it would be using W11. rng.Start = rng.End - 2; rng.Delete(); range.End = rng.End; // Now we should have same range as if W11 had been used with the simple Range.InsertXML only. if (use_target_p_markup_for_last_para) range.Paragraphs.Last.Range.ParagraphFormat = pf; }