different format into one single line Interop.word

前端 未结 6 887
深忆病人
深忆病人 2020-12-11 04:45

I\'ve been trying to figure out how to insert 2 different formats into the same paragraph using interop.word in c# like this:

hello planet earth her

6条回答
  •  [愿得一人]
    2020-12-11 05:41

    I know this is an old thread, but I thought I'd post here anyway for those that come across it via Google (like I did). I got most of the way to a solution with krillgar's approach, but I had trouble because some of my text contains newlines. Accordingly, this modification worked best for me:

    private void WriteText(string text)
        {
            var para = doc.Content.Paragraphs.Add();
            var start = para.Range.Start;
            var end = para.Range.Start + text.IndexOf(":");
            para.Range.Text = text;
            para.Range.Font.Bold = 0;
            para.Range.InsertParagraphAfter();
    
            if(text.Contains(":")){
                var rngBold = doc.Range(start, end);
                rngBold.Bold = 1;
            }
        }
    

    The key difference is that I calculate start and end earlier in the function. I can't quite put my finger on it, but I think if your new text has newlines in it, the later calculation of start/end messes something up.

    And obviously my solution is intended for text with the format:

    Label: Data

    where Label is to be bolded.

提交回复
热议问题