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



我有这一行:

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示例

所以有办法在C#

中做到这一点

我找到了一个解决方案:

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:rn" + ex.Message);
            return false;
        }
    }
    return true;
}

相关内容

  • 没有找到相关文章

最新更新