首页 > 解决方案 > 如何知道实际单元格是否有边框顶部

问题描述

如果每个给定的单元格都有任何类型的 BORDER TOP 并且单元格为空,我需要检查工作表

这是我到目前为止所做的......

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(original_file_path + file_name + xls);

//Work on sheet number 2
Microsoft.Office.Interop.Excel.Worksheet x = workbook.Worksheets[2];

INT MAX_ROW = usedRange.Rows.Count;
INT MAX_COL = usedRange.Columns.Count;

for (int row = 1; row <= MAX_ROW; row++)
{
 for (int col = 1; col <= MAX_COL; col++)
 {
//The following line is pseudocode since i have no idea how to use border property. This checks if the given cell is empty and if the border top is null
   if(x.Cells[row,col].Borders.topBorder == false && x.Cells[row,col].Value == null)
   {
   //The thing that i want to do with this is replace that cell value to the one located on Cells [row -1, col]
     x.Cells[row,col].value = x.Cells[row -1, col].value;
   }else {
   Console.WriteLine("nothing to do here");
   }

 }
}

标签: c#excelparsinginteropcell

解决方案


这是一种快速的方法,您可以根据自己的喜好进行调整,它应该为您提供所需的逻辑......实际上,我只是在查看单元格顶部边框的线条样式。如果它是“无”,那么其他属性并不重要。

您在正确的轨道上,但是Borders是一个索引器,并且您将它提供给有问题的边框并评估 LineStyle 属性。

private bool HasTopBorder(Excel.Range r)
{
    return ((Excel.XlLineStyle)r.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle) !=
        Excel.XlLineStyle.xlLineStyleNone;
}

有趣的是,LineStyle返回一个整数,因此是强制转换。这意味着您可以简单地弄清楚枚举的用途xlLineStyleNone并进行比较,但是无论您在效率上获得什么,您都会在透明度方面失去更多。

再次,如果它在您的代码中有意义,则将其内联,但我想隔离您需要的逻辑。


推荐阅读