簡體   English   中英

C# Excel 互操作 - 如何檢查范圍內的單個單元格是否具有單元格邊界?

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

我目前正在編寫一個 C# 應用程序來解析 excel 工作表。 我有這些循環,它們遍歷工作表中的每個單元格並將它們的值打印到控制台:

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");
       }
   }
 }

我的目標如下:我想找到具有頂部和左側單元格邊框的第一個單元格的地址(行和列)。 不幸的是,我無法弄清楚如何在不更改或設置它們的情況下檢查單個單元格上的邊框 - 我認為它會像

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

但不幸的是,這段代碼只會讓應用程序崩潰。 有誰知道檢查單個單元格是否包含邊框的簡單方法?

您快到了。 由於 LineStyle 屬性是動態的(即編譯器不知道它是哪種 object),您需要將其顯式轉換為 XlLineStyle 以防止運行時錯誤:

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

現在我確定它是動態的是有原因的,上面的代碼可能會在某些情況下崩潰,但我對 Excel 互操作不夠熟悉,無法告訴你什么時候會發生。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM