c#excel interop如何知道实际单元格的边界是否在顶部

问题描述 投票:1回答:1

我需要在工作表中检查每个给定的单元格是否具有任何类型的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# excel parsing interop cell
1个回答
0
投票

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

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

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

有趣的是,LineStyle返回一个整数,因此是强制类型转换。这意味着您可以简单地找出xlLineStyleNone的枚举并进行比较,但是无论效率如何提高,透明度都会损失更大。

同样,如果在代码中有意义,请内联此代码,但是我想隔离出所需的逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.