【教程】Excel控件Spire.XLS 教程:在C#,VB.NET中添加Excel边框

时间:2022-08-12 14:01:00

在Excel中,可以将边框添加到单个单元格以强调数据,标记汇总值或单元格区域中的数据。边界也可以用不同的线条样式和颜色进行格式化。本文介绍了如何使用Spire.XLS将边框样式应用于Excel单元格。

Step 1: 创建一个工作簿实例并获取第一个工作表。

Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

Step 2: 获取您想要应用边框样式的单元格区域。

CellRange range = sheet.Range["B2:D4"];

Step 3: 调用BorderInside()和BorderAround()方法将样式应用于范围内和范围的边界。 若要将边框添加到顶部,底部,左侧和右侧,请使用边框[BordersLineType.EdgeTop] .LineStyle属性,边框[BordersLineType.EdgeBottom] .LineStyle属性等。

range.BorderInside(LineStyleType.Thin, Color.Blue);
range.BorderAround(LineStyleType.Medium, Color.Blue);

Step 4: 保存到文件。

wb.SaveToFile("result.xlsx", ExcelVersion.Version2013);

输出:

【教程】Excel控件Spire.XLS 教程:在C#,VB.NET中添加Excel边框

完整代码:

[C#]

Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

//apply border style to the range B2:D4
CellRange range = sheet.Range["B2:D4"];
range.BorderInside(LineStyleType.Thin, Color.Blue);
range.BorderAround(LineStyleType.Medium, Color.Blue);

//apply border style to the range D7:F9
range = sheet.Range["D7:F9"];
range.Borders.LineStyle = LineStyleType.Double;
range.Borders[BordersLineType.DiagonalDown].LineStyle = LineStyleType.None;
range.Borders[BordersLineType.DiagonalUp].LineStyle = LineStyleType.None;

//apply border style to the range F12:H14
range = sheet.Range["F12:H14"];
range.Merge();
range.BorderAround(LineStyleType.Thin);
range.Borders[BordersLineType.DiagonalDown].LineStyle = LineStyleType.Thin;
range.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thick;
range.Borders.Color = Color.Red;

wb.SaveToFile("result.xlsx", ExcelVersion.Version2013);

[VB.NET]

Dim wb As Workbook = New Workbook()
Dim sheet As Worksheet = wb.Worksheets(0)

'apply border style to the range B2:D4
Dim range As CellRange = sheet.Range("B2:D4")
range.BorderInside(LineStyleType.Thin, Color.Blue)
range.BorderAround(LineStyleType.Medium, Color.Blue)

'apply border style to the range D7:F9
range = sheet.Range("D7:F9")
range.Borders.LineStyle = LineStyleType.Double
range.Borders(BordersLineType.DiagonalDown).LineStyle = LineStyleType.None
range.Borders(BordersLineType.DiagonalUp).LineStyle = LineStyleType.None

'apply border style to the range F12:H14
range = sheet.Range("F12:H14")
range.Merge()
range.BorderAround(LineStyleType.Thin)
range.Borders(BordersLineType.DiagonalDown).LineStyle = LineStyleType.Thin
range.Borders(BordersLineType.EdgeBottom).LineStyle = LineStyleType.Thick
range.Borders.Color = Color.Red

wb.SaveToFile("result.xlsx", ExcelVersion.Version2013)

点击下载Spire.XLS