C#/VB.NET: Apply or Remove Data Validation in Excel

2022-09-22 08:42:00 Written by  support iceblue
Rate this item
(0 votes)

The data validation feature in Excel allows the user to control what data can be entered into a cell. For example, you could use data validation to make sure a numeric entry is between 1 and 5, make sure a text entry is less than 20 characters, or make sure the value entered in a cell is from a predefined list. In this article, you will learn how to apply or remove data validation in Excel in C# and VB.NET using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Apply Data Validation to Excel Cells

The following are the steps to add various types of data validation to cells using Spire.XLS for .NET.

  • Create a Workbook object
  • Get the first worksheet through Workbook.Worksheets[index] property.
  • Get a specific cell through Worksheet.Range property.
  • Set the data type allowed in the cell through CellRange.DataValidation.AllowType property. You can select Integer, Time, Date, TextLength, Decimal, etc. as the data type.
  • Set the comparison operator through CellRange.DataValiation.CompareOperator property. The comparison operators include Between, NotBetween, Less, Greater, and Equal.
  • Set one or two formulas for the data validation through CellRange.DataValidation.Formula1 and CellRange.DataValidation.Formula2 properties.
  • Set the input prompt through CellRange.DataValidation.InputMessage property.
  • Save the workbook to an Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Xls;

namespace ApplyDataValidation
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Insert text in cells
            sheet.Range["B2"].Text = "Number Validation:";
            sheet.Range["B4"].Text = "Date Validation:";
            sheet.Range["B6"].Text = "Text Length Validation:";
            sheet.Range["B8"].Text = "List Validation:";
            sheet.Range["B10"].Text = "Time Validation:";

            //Add a number validation to C2
            CellRange rangeNumber = sheet.Range["C2"];
            rangeNumber.DataValidation.AllowType = CellDataType.Integer;
            rangeNumber.DataValidation.CompareOperator = ValidationComparisonOperator.Between;
            rangeNumber.DataValidation.Formula1 = "1";
            rangeNumber.DataValidation.Formula2 = "10";
            rangeNumber.DataValidation.InputMessage = "Enter a number between 1 and 10";
            rangeNumber.Style.KnownColor = ExcelColors.Gray25Percent;

            //Add a date validation to C4
            CellRange rangeDate = sheet.Range["C4"];
            rangeDate.DataValidation.AllowType = CellDataType.Date;
            rangeDate.DataValidation.CompareOperator = ValidationComparisonOperator.Between;
            rangeDate.DataValidation.Formula1 = "1/1/2010";
            rangeDate.DataValidation.Formula2 = "12/31/2020";
            rangeDate.DataValidation.InputMessage = "Enter a date between 1/1/2010 and 12/31/2020";
            rangeDate.Style.KnownColor = ExcelColors.Gray25Percent;

            //Add a text length validation to C6
            CellRange rangeTextLength = sheet.Range["C6"];
            rangeTextLength.DataValidation.AllowType = CellDataType.TextLength;
            rangeTextLength.DataValidation.CompareOperator = ValidationComparisonOperator.LessOrEqual;
            rangeTextLength.DataValidation.Formula1 ="5";
            rangeTextLength.DataValidation.InputMessage = "Enter text lesser than 5 characters";
            rangeTextLength.Style.KnownColor = ExcelColors.Gray25Percent;

            //Apply a list validation to C8
            CellRange rangeList = sheet.Range["C8"];
            rangeList.DataValidation.Values = new String[] { "United States", "Canada", "United Kingdom", "Germany" };
            rangeList.DataValidation.IsSuppressDropDownArrow = false;
            rangeList.DataValidation.InputMessage ="Choose an item from the list";
            rangeList.Style.KnownColor =ExcelColors.Gray25Percent;

            //Apply a time validation to C10
            CellRange rangeTime = sheet.Range["C10"];
            rangeTime.DataValidation.AllowType = CellDataType.Time;
            rangeTime.DataValidation.CompareOperator = ValidationComparisonOperator.Between;
            rangeTime.DataValidation.Formula1 = "9:00";
            rangeTime.DataValidation.Formula2 = "12:00";
            rangeTime.DataValidation.InputMessage = "Enter a time between 9:00 and 12:00";
            rangeTime.Style.KnownColor = ExcelColors.Gray25Percent;

            //Auto fit width of column 2
            sheet.AutoFitColumn(2);

            //Set the width of column 3
            sheet.Columns[2].ColumnWidth = 20;

            //Save to file
            workbook.SaveToFile("ApplyDataValidation.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Apply or Remove Data Validation in Excel

Remove Data Validation from Excel Cells

Below are the steps to remove data validation from the specified cell using Spire.XLS for .NET.

  • Create a Workbook object.
  • Load the Excel file containing data validation using Workbook.LoadFromFile() method.
  • Get the first worksheet though Workbook.Worksheets[index] property.
  • Create an array of rectangles, which is used to locate the cells where the validation will be removed.
  • Remove the data validation from the selected cells using Worksheet.DVTable.Remove() method.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;
using System.Drawing;

namespace RemoveDataValidation
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

            //Load a sample Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\ApplyDataValidation.xlsx");

            //Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //Create an array of rectangles, which is used to locate the ranges in worksheet
            Rectangle[] rectangles = new Rectangle[]{

                //one Rectangle(startColumnIndex, startRowIndex, endColumnIndex, endRowIndex) specifies a  cell range to remove data validation
                //the column or row index starts at 0
                new Rectangle(0, 0, 2, 9)
            };

            //Remove the data validation from the selected cells
            worksheet.DVTable.Remove(rectangles);

            //Save the workbook to an Excel file
            workbook.SaveToFile("RemoveDataValidation.xlsx");
        }
    }
}

C#/VB.NET: Apply or Remove Data Validation in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 22 September 2022 01:14