Get Cell Type in Excel in C#

2019-03-21 06:35:54 Written by  support iceblue
Rate this item
(0 votes)

Cell type refers to the data type in a cell. There are six cell types in Spire.XLS, i.e. String, Number, Formula, Boolean, Error and Blank. This article is going to show you how to get the cell types of specified cells in an Excel file using Spire.XLS.

Detail steps

Step 1: Create a Workbook instance and load the Excel file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");

Step 2: Get the second worksheet.

Worksheet sheet = workbook.Worksheets[1];

Step 3: Get the cell types of the cells in range "A2:A7".

foreach (CellRange range in sheet.Range["A2:A7"])
{
    XlsWorksheet.TRangeValueType cellType = sheet.GetCellType(range.Row, range.Column, false);
    sheet[range.Row, range.Column+1].Text = cellType.ToString();
    sheet[range.Row, range.Column + 1].Style.Font.Color = Color.Red;
    sheet[range.Row, range.Column+1].Style.Font.IsBold = true;
}

Step 4: Save the file.

workbook.SaveToFile("GetCellType.xlsx", ExcelVersion.Version2013);

Output:

Get Cell Type in Excel in C#

Full code:

using System.Drawing;
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet;

namespace GetCellType
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Input.xlsx");

            //Get the second worksheet
            Worksheet sheet = workbook.Worksheets[1];

            //Get the cell types of the cells in range “A2:A7”
            foreach (CellRange range in sheet.Range["A2:A7"])
            {
                XlsWorksheet.TRangeValueType cellType = sheet.GetCellType(range.Row, range.Column, false);
                sheet[range.Row, range.Column+1].Text = cellType.ToString();
                sheet[range.Row, range.Column + 1].Style.Font.Color = Color.Red;
                sheet[range.Row, range.Column+1].Style.Font.IsBold = true;
            }            

            //Save the file
            workbook.SaveToFile("GetCellType.xlsx", ExcelVersion.Version2013);            
        }
    }
}

Additional Info

  • tutorial_title:
Last modified on Friday, 12 April 2024 01:01