Excel Interop – 绘制范围内的所有边界

我从Microsoft的文档中看到,我可以使用“xlBordersIndex”属性访问单元格的特定边界边界,例如,为单元格的左边缘设置边框样式:

range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous; 

但是如果我只想画出所有的边界呢? 我努力了

 range.BorderAround2(); 

但这只是在范围本身附近画一个盒子,据我所知。 所以然后我试了

 range.Cells.BorderAround2(); 

认为它会通过范围内的每个单元格,并将每个单元格周围的所有边界。 这不是发生了什么。 因此,为了获得一个范围内的所有单元格的所有边界,我必须手动访问四个边界索引中的每一个?

 private void AllBorders(Excel.Borders _borders) { _borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous; _borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous; _borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous; _borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous; _borders.Color = Color.Black; } 

我还不熟悉C#,但在VBA中有Range.Borders(xlInsideVertical)Range.Borders(xlInsideHorizontal)属性。 尝试使用macroslogging器并为任何工作簿区域应用所有边框。 也许这会有所帮助。

 oRange = SHEET2.get_Range("a1", "a10"); oRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous; oRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous; oRange.Borders.get_Item(Excel.XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlContinuous; oRange.Borders.get_Item(Excel.XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlContinuous; 

最后我得到了它。 我这样做也不会影响性能。 我正在做一个简单的excel来解释一下:

之前

在这里输入图像说明

我设法将范围以A1:C4的formsdynamic存储在exRange中,并使用下面的代码给出边界

 ((Range)excelSheet.get_Range(exRange)).Cells.Borders.LineStyle = XlLineStyle.xlContinuous; 

在这里输入图像说明

 For Each range In ranges For Each row As Range In .Range(range).Rows row.Cells.BorderAround(XlLineStyle.xlContinuous) row.Cells.Borders.Item(XlBordersIndex.xlInsideHorizontal).LineStyle = XlLineStyle.xlContinuous row.Cells.Borders.Item(XlBordersIndex.xlInsideVertical).LineStyle = XlLineStyle.xlContinuous Next Next 

为什么不简单地做:

 Excel.Range tRange = xlWorkSheet.UsedRange; tRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous; tRange.Borders.Weight = Excel.XlBorderWeight.xlThin; 

注意:在行和单元格(范围)之后应用边框填充数据以获得范围只需使用函数.UsedRange()

 Microsoft.Office.Interop.Excel.Range tRange = xlWorkSheet.UsedRange; tRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; tRange.Borders.Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;