将样式设置为合并单元格C#excel的范围

时间:2016-11-25 19:34:31

标签: c# excel styles

我有这一行:

excelObject.workSheet.Range["A" + index + ":AA" + index].Style = "Found";

并且

Excel.Style oStyle;
oStyle = excelObject.application.ActiveWorkbook.Styles.Add("Found");
oStyle.Font.Bold = true;
oStyle.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);

但是当它尝试在合并单元格的范围内设置样式时,它会抛出错误:"我们无法对合并的单元格执行此操作。"

但如果我在VBA中尝试相同的代码,它可以工作: VBA example

那么有没有办法在C#

中做到这一点

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

try
{
    excelObject.workSheet.Range["A" + index + ":AA" + index].Style = "Found";
}
catch (Exception ex)
{
    if (ex.Message.Equals("We can't do that to a merged cell."))
    {
        /*
            1 means A 
            27 means AA
            index is the current row
        */
        if (!setStyleInNoMergedCells(1, 27, index, "Found"))
        {
            Console.WriteLine("Fail);
        }
    }
    else
    {
        Console.WriteLine("Fail);
    }
}

private Boolean setStyleInNoMergedCells(int startRange,int endRange, int row,String styleString)
{
    for (int i = startRange; i <= endRange; i++)
    {
        try
        {
            Excel.Range rng = (Excel.Range) excelMDB.workSheet.Cells[row, i];
            if (rng.MergeCells)
            {
                Excel.Range rngMerged = rng.MergeArea;
                Excel.Range rngStart = rngMerged.Cells[1, 1];
                string value = rngStart.Value;
                rng.UnMerge();

                foreach (Excel.Range cell in rngMerged)
                {
                    cell.Value = value;
                }

                rng.Style = styleString;
            }
            else
            {
                rng.Style = styleString;
            }
        }
        catch (Exception ex)
        {
            System.Console.Write("[setStyleInNoMergedCells] error:\r\n" + ex.Message);
            return false;
        }
    }
    return true;
}