本文介绍了C#Excel Interop-如何检查范围内的单个单元格是否具有单元格边框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个C#应用程序来解析excel工作表.我有这些循环,这些循环遍历工作表中的每个单元格并将其值打印到控制台:

I am currently writing a C# application to parse excel worksheets. I have these loops, which iterate through every cell in the worksheet and print their values to the console:

for (int i = 1; i <= excelRange.Height; i++) {
   for (int j = 1; j <= excelRange.Width; j++) {
     if (j == 1)
       Console.Write("\r\n");
     if (excelRange.Cells[i, j] != null && excelRange.Cells[i, j].Value2 != null)
       if (excelRange.Cells[i, j].Value2.ToString() == "-2146826265") {
         Console.Write("\t");
       }
       else {
         Console.Write(excelRange.Cells[i, j].Value2.toString() + "\t");
       }
   }
 }

我的目标是:我想找到具有顶部和左侧单元格边框的第一个单元格的地址(行和列).不幸的是,我无法弄清楚如何在不更改或设置边界的情况下检查单个单元格的边界,我想这就像

My goal is the following: I want to find the address (row and column) of the first cell that has a top and left cell border. Unfortunately, I cannot figure out how to check what the borders are on a single cell without changing or setting them-- I thought it would be something like

excelRange.Cells [i,j] .Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle == Excel.XlLineStyle.xlContinuous;

但是不幸的是,这段代码只是使应用程序崩溃.有谁知道一种简单的方法来检查单个单元格是否包含边框?

But unfortunately, this code simply crashes the application. Does anyone know a straightforward way to check if a single cell contains borders?

推荐答案

您快到了.由于LineStyle属性是动态的(即编译器不知道它是哪种对象),因此您需要将其显式转换为XlLineStyle,以防止发生运行时错误:

You're almost there. Since the LineStyle property is dynamic (i.e. the compiler doesn't know what kind of object it is), you'll need to explicitly cast it to XlLineStyle in order to prevent a runtime error:

var cellLineStyle = (Excel.XlLineStyle)excelRange.Cells[i,j].Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle;
if (cellLineStyle == Excel.XlLineStyle.xlContinuous) {
    // do stuff
}

现在,我确定它是动态的,这是有原因的,并且上面的代码在某些情况下可能会崩溃,但是我对Excel interop不够了解,无法告诉您何时会发生这种情况.

Now I'm sure it's dynamic for a reason, and the above code will probably blow up in certain circumstances, but I'm not familiar enough with Excel interop to tell you when that'll happen.

这篇关于C#Excel Interop-如何检查范围内的单个单元格是否具有单元格边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:13