1.添加NPOI组件,利用VS自带的NuGet管理,右键项目选择管理NuGet程序包,搜索NPOI选择合适版本安装即可,安装完成会自动添加引用。
2.在使用该组建的页面引入命名空间:
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
3.项目中新建了一个操作Excel文件的类HandleExcel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
namespace AddressList.lib
{
public class HandleExcel
{
#region 读取Excel文件,返回数据集合
/// <summary>
/// 读取Excel文件,返回数据集合
/// </summary>
/// <param name="fname">要读取的Excel文件地址</param>
public List<excels> ReadExcel(string fname)
{
//首先根据需要读取的文件创建一个文件流对象
using (FileStream fs = File.OpenRead(fname))
{
IWorkbook workbook = null;
//这里需要根据文件名格式判断一下
//HSSF只能读取xls的
//XSSF只能读取xlsx格式的
if (Path.GetExtension(fs.Name) == ".xls")
{
workbook = new HSSFWorkbook(fs);
}
else if (Path.GetExtension(fs.Name) == ".xlsx")
{
workbook = new XSSFWorkbook(fs);
}
//用来存储读取出数据的集合
List<excels> list = new List<excels>();
//因为Excel表中可能不止一个工作表,这里为了演示,我们遍历所有工作表
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
//得到当前sheet
ISheet sheet = workbook.GetSheetAt(i);
//也可以通过GetSheet(name)得到
//遍历表中所有的行
//注意这里加1,这里得到的最后一个单元格的索引默认是从0开始的
for (int j = 0; j < sheet.LastRowNum + 1; j++)
{
//得到当前的行
IRow row = sheet.GetRow(j);
if (row.Cells.Count() > 0)
{
excels ex = new excels();
ICell cell = row.GetCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.SetCellType(CellType.String);
ex.gsname = cell.StringCellValue;
cell = row.GetCell(1, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.SetCellType(CellType.String);
ex.lxname = cell.StringCellValue;
cell = row.GetCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.SetCellType(CellType.String);
ex.prof = cell.StringCellValue;
cell = row.GetCell(3, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.SetCellType(CellType.String);
ex.phone = cell.StringCellValue;
cell = row.GetCell(4, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.SetCellType(CellType.String);
ex.address = cell.StringCellValue;
cell = row.GetCell(5, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.SetCellType(CellType.String);
ex.xingzhi = cell.StringCellValue;
cell = row.GetCell(6, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.SetCellType(CellType.String);
ex.product = cell.StringCellValue;
list.Add(ex);
}
//遍历每行所有的单元格
//注意这里不用加1,这里得到的最后一个单元格的索引默认是从1开始的
/*for (int k = 0; k < row.LastCellNum; k++)
{
//得到当前单元格
ICell cell = row.GetCell(k, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.SetCellType(CellType.String);
s += cell.StringCellValue;
}*/
}
}
return list;
}
}
#endregion
}
}
4.使用该类进行读取即可。
注:其中excels是自己建的一个实体类,可以替换成其它的。