一、项目中引用NPOI包
二、代码部分
static void Main(string[] args)
{
Read();
Console.ReadLine();
}
public static void Read()
{
//文件路径
var files = @"E:\File\Stu.xlsx";
using (FileStream file = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = null;
if (files.IndexOf(".xlsx") > 0)
{
workbook = new XSSFWorkbook(file);
}
// 2003版本
else if (files.IndexOf(".xls") > 0)
{
workbook = new HSSFWorkbook(file);
}
if (workbook is null)
{
throw new Exception($"该文件后缀名只能是.xlsx或.xls");
}
//索引从0 开始,以下为获取第一个工作表
var sheet1 = workbook.GetSheetAt(0);
//索引从0开始,以下为获取到第2行第2列的内容,取到值不能直接用ToString(),如果是时间类型会取不全值
var stuName = GetValueByType(sheet1.GetRow(1).GetCell(1));
Console.WriteLine(stuName);
}
}
/// <summary>
/// 判断类型取值
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
public static string GetValueByType(ICell cell)
{
if (cell.CellType == CellType.Numeric)
{
//NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型
if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型
{
return cell.DateCellValue.ToString();
}
else//其他数字类型
{
return cell.NumericCellValue.ToString();
}
}
else if (cell.CellType == CellType.Blank)//空数据类型
{
return string.Empty;
}
else //其他类型都按字符串类型来处理
{
return cell.StringCellValue;
}
}