使用Excel Interop c#用粗体替换单词

时间:2012-05-01 01:26:18

标签: c# excel replace interop bold

我使用以下内容搜索整个Excel工作表,并将'req'替换为'required':

oSheet.Cells.Replace("req", "requirement");

而不是替换req这个词,我想加粗它。我怎样才能做到这一点?我知道这是错的,但理论上我想做以下事情:

oSheet.Cells.Replace("req", "<b>req</b>");

感谢。

2 个答案:

答案 0 :(得分:3)

我假设您要将单元格中的单个文本项目设置为粗体,这比首次出现时要复杂一些。以下将解决这个问题:

    public void FindTextAndSetToBold(string text)
    {
        Excel.Range currentFind = null;
        Excel.Range firstFind = null;

        // Find the first occurrence of the passed-in text

        currentFind = oSheet.Cells.Find(text, Missing.Value, Excel.XlFindLookIn.xlValues,
            Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext,
            false, Missing.Value, Missing.Value);

        while (currentFind != null)
        {
            // Keep track of the first range we find

            if (firstFind == null)
            {
                firstFind = currentFind;
            }
            else if (currentFind.get_Address(Missing.Value, Missing.Value, Excel.XlReferenceStyle.xlA1,
                Missing.Value, Missing.Value) ==
                firstFind.get_Address(Missing.Value, Missing.Value, Excel.XlReferenceStyle.xlA1,
                Missing.Value, Missing.Value))
            {
                // We didn't move to a new range so we're done

                break;
            }

            // We know our text is in first cell of this range, so we need to narrow down its position

            string searchResult = currentFind.get_Range("A1").Value2.ToString();
            int startPos = searchResult.IndexOf(text);

            // Set the text in the cell to bold

            currentFind.get_Range("A1").Characters[startPos + 1, text.Length].Font.Bold = true;

            // Move to the next find

            currentFind = oSheet.Cells.FindNext(currentFind);
        }
    }

部分取自here并修改。

答案 1 :(得分:0)

这样做你想要的吗? (预先设定)

Application.ReplaceFormat.Font.FontStyle = "Bold"