C# Excel Interop -- 如何检查范围内的单个单元格是否有单元格边框?
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 属性 是动态的(即编译器不知道它是什么类型的对象),您需要将其显式转换为 XlLineStyle 以防止运行时错误:
var cellLineStyle = (Excel.XlLineStyle)excelRange.Cells[i,j].Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle;
if (cellLineStyle == Excel.XlLineStyle.xlContinuous) {
// do stuff
}
现在我确定它是动态的是有原因的,上面的代码在某些情况下可能会崩溃,但我对 Excel interop 不够熟悉,无法告诉你什么时候会发生.
我目前正在编写一个 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 属性 是动态的(即编译器不知道它是什么类型的对象),您需要将其显式转换为 XlLineStyle 以防止运行时错误:
var cellLineStyle = (Excel.XlLineStyle)excelRange.Cells[i,j].Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle;
if (cellLineStyle == Excel.XlLineStyle.xlContinuous) {
// do stuff
}
现在我确定它是动态的是有原因的,上面的代码在某些情况下可能会崩溃,但我对 Excel interop 不够熟悉,无法告诉你什么时候会发生.