在读取Excel单元格的数据之前,有时候需要判断单元格的数据类型。在Spire.XLS中有String、Number、Formula、Boolean、Error和Blank六种数据类型,分别对应字符串型、数值型、公式型、布尔型、错误和空值。这篇文章将介绍如何使用Spire.XLS获取单元格的数据类型。
C#
using System.Drawing;
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet;
namespace GetCellType
{
class Program
{
static void Main(string[] args)
{
//创建Workbook实例
Workbook workbook = new Workbook();
//加载Excel文档
workbook.LoadFromFile("Input.xlsx");
//获取第二张工作表
Worksheet sheet = workbook.Worksheets[1];
//获取指定范围内的单元格的数据类型
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;
}
//保存文档
workbook.SaveToFile("GetCellType.xlsx", ExcelVersion.Version2013);
}
}
}
VB.NET
Imports System.Drawing
Imports Spire.Xls
Imports Spire.Xls.Core.Spreadsheet
Namespace GetCellType
Class Program
Private Shared Sub Main(args As String())
'创建Workbook实例
Dim workbook As New Workbook()
'加载Excel文档
workbook.LoadFromFile("Input.xlsx")
'获取第二张工作表
Dim sheet As Worksheet = workbook.Worksheets(1)
'获取指定范围内的单元格的数据类型
For Each range As CellRange In sheet.Range("A2:A7")
Dim cellType As XlsWorksheet.TRangeValueType = 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
Next
'保存文档
workbook.SaveToFile("GetCellType.xlsx", ExcelVersion.Version2013)
End Sub
End Class
End Namespace
结果文档: