2017-07-17 167 views
0

我需要修改的代碼創建一個Excel電子表格並在單元格中插入搜索結果。邏輯找到匹配並複製代碼中的整個行。然後它用<comma>替換逗號,不知道爲什麼,但那不重要。我需要突出顯示此搜索結果中的特定單詞,最好是粗體和紅色。查看下面的例子,搜索參數是COMPUTE,結果是整行代碼,這是設計的。格式化Excel電子表格單元格內的文本

)WITH(PAD_INDEX = OFF STATISTICS_NORE COMPUTE = OFF IGNORE_DUP_KEY = OFF ALLOW_ROW_LOCKS = ON

我有一個分割 '語境' 可變成字符串數組,並且如果匹配的一些基本代碼被發現它應該格式化這個詞 - 但是這是我的挑戰所在。

我發現了很多關於如何格式化整個單元或行,但不是單元格內文本的例子。

  string[] wordList = context.Split(' '); 
      StringBuilder reassembleContext = new StringBuilder(); 
      int i = 0; 
      regexPattern = new Regex(pattern.ToString(CultureInfo.InvariantCulture)); 

      foreach (string word in wordList) 
      { 
       var matches = Regex.Matches(word, pattern.ToString(), RegexOptions.IgnoreCase); 
       if (matches.Count > 0) 
       { 
        wordList[i] = "<b>" + word + "</b>"; // Clearly this does not work... 
       } 

       reassembleContext.Append(wordList[i]); 
       reassembleContext.Append(" "); 
       i++; 
      } 

      context = reassembleContext.ToString(); 
+0

我什麼都不知道在'C#'爲Excel編程,但在Excel本身,你可以格式化提供的單元格內容是文本字符串,而不是一個公式的結果的單元格中的文本。在VBA中,您將使用characters屬性來確定哪些字符的格式不同。 –

+0

是這個Interop.Excel,還是OpenXML,或其他什麼..? – Slai

+0

它是Interop.Excel,但可以更改。 – Risho

回答

1
  1. 最簡單的辦法是將HTML中的剪貼板,並將其粘貼:

    System.Windows.Forms.Clipboard.SetText("<html>a<b>b</b>c"); 
    worksheet.Range["A1"].PasteSpecial(); 
    
  2. 的常用方法是使用電池的.Characters屬性來設置格式:

    worksheet.Range["A1"].Characters[38, 7].Font.Bold = true; 
    
  3. 另一種方法是使用Excel的Replace格式:

    application.ReplaceFormat.Font.Bold = true; 
    range.Replace("COMPUTE", "COMPUTE", XlLookAt.xlPart, ReplaceFormat: true); 
    
相關問題