C# – Add Borders for Cells

Borders play an important role in Excel formatting, which can make the data in borders be more obvious. Also, if we don't any borders, the data will be printed without any lines, just like the following image.

Although it presents necessary information, the data is not so clear and the appearance is not great.

In this post, I will show one method to add borders for cells with C#. In this example, I have prepared an Excel file which includes a part of student information and the data is nearly no formatted. Therefore, I will format data firstly and then add borders.

Note: this method is based on a component, Spire.XLS. So, download and install it at the beginning.


  1. Load file which I want to add borders.
  2. Set cells format, including font style, size and cell background.
  3. Add borders for cells, including top, left, right and bottom. Then, set borders color.
  4. Save and Launch File.

Using the Code:

using System;
using System.Drawing;
using Spire.Xls;

namespace ExcelBorders
    class Borders
        static void Main(string[] args)
            Workbook workbook = new Workbook();

            //Load File and Initialize Worksheet
            workbook.LoadFromFile(@"D:\work\My Documents\StInfo.xlsx");
            Worksheet sheet = workbook.Worksheets[0];            
            //Set Data Format
            sheet.Range["A1:E1"].Style.Font.Size= 14;
            sheet.Range["A1:E1"].Style.Font.IsBold = true;
            sheet.Range["A1:E1"].Style.Color = Color.LightCyan;

            sheet.Range["A2:E9"].Style.Font.Size = 12;
            sheet.Range["A2:E9"].Style.Color = Color.WhiteSmoke;

            //Add Borders for All Cells
            sheet.Range["A1:E9"].Style.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:E9"].Style.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:E9"].Style.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:E9"].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:E9"].Style.Borders.Color = Color.DarkBlue;

            //Save and Launch File
            workbook.SaveToFile("Borders.xlsx", ExcelVersion.Version2010);

After running, we can get the result as following:

In Excel:

Print View:


Click Here to Learn More about Spire.XLS
Click Here to Download Spire.XLS


One thought on “C# – Add Borders for Cells

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s