C# Excel Interop — How to check if a single cell in a range has cell borders?

空扰寡人 提交于 2021-01-28 10:52:43

问题


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?


回答1:


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
}

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.



来源:https://stackoverflow.com/questions/58547106/c-sharp-excel-interop-how-to-check-if-a-single-cell-in-a-range-has-cell-borde

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!