编程语言
首页 > 编程语言> > c# – 在Excel工作表中为非连续单元格着色

c# – 在Excel工作表中为非连续单元格着色

作者:互联网

这是发生的事情:

xlValues设置为Excel.Range对象.

我也试过以下,都给了我同样的错误:

//xlValueRange = xlSheet...
.get_Range("A1:A5,A15:A25,A50:A65");
.UsedRange.Range["A1:A5,A15:A25,A50:A65"];
.Range["A1:A5,A15:A25,A50:A65"];

xlApp.ActiveWorkbook.ActiveSheet.Range["A1:A5,A15:A25,A50:A65"];
//I have also tried these alternatives with ".Select()" after the brackets and 
//", Type.Missing" inside the brackets

//This works though...
xlSheet.Range["A1:A5"];

我正在尝试重新着色excel表中的特定单元格,我已经通过使用两个循环找到了解决方案,但它太慢了.通过一个30 000个单元格的列需要几分钟.

我之前从未做过这样的事情,我使用了this教程让我开始.

此解决方案使用bool数组,将要着色的单元格设置为true.(重新着色)

//using Excel = Microsoft.Office.Interop.Excel;

xlApp = new Excel.Application();
xlApp.Visible = true;
xlBook = xlApp.Workbooks.Add(Type.Missing);
xlSheet = (Excel.Worksheet)xlBook.Sheets[1];

for (int i = 1; i < columns + 1; i++)
{
    for (int j = 1; j < rows + 1; j++)
    {
        if (recolored[j, i])
            xlSheet.Cells[j+1, i+1].Interior.Color = Excel.XlRgbColor.rgbRed;
        }
    }
}

我想做的是这样的事情:

Excel.XlRgbColor[,] color;
//Loop to fill color with Excel.XlRgbColor.rgbRed at desired cells.

var startCell = (Excel.Range)xlSheet.Cells[1, 1];
var endCell = (Excel.Range)xlSheet.Cells[rows, columns];
var xlRange = xlSheet.Range[startCell, endCell];

xlRange.Interior.Color = color;

这个给了我最后一行的错误;

类型不匹配. (HRESULT异常:0x80020005(DISP_E_TYPEMISMATCH))

我的第一个猜测是创建一个Excel.Range对象,它覆盖我想要红色的单元格并使用该对象代替xlRange,如下所示:

RangeObject.Interior.Color = Excel.XlRgbColor.rgbRed;

我不知道是否可以制作一个像这样的间隙的Excel.Range对象,但我可以在这个上使用一些帮助.

解决方法:

我有同样的问题,事实证明这是一个糟糕的列表分隔符 – 在我的情况下,而不是逗号应该有一个分号.

而不是

.Range["A1:A5,A15:A25,A50:A65"];

尝试:

private string listSep = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;

.Range["A1:A5" + listSep + "A15:A25" + listSep + "A50:A65"];

标签:c,excel,office-interop
来源: https://codeday.me/bug/20190520/1142626.html