(1)下载地址:https://archive.codeplex.com/?p=npoi
或者:
链接:https://pan.baidu.com/s/1nlcO0YH1rWFcQVOYLjocQQ
提取码:opgt
(2)下载后解压,进入releases->18,将里面的文件重命名为.RAR文件,再解压这个文件,就得到了好多dll。
(3)在C#项目中,添加(在dotnet4文件夹的)3个dll引用:
(4)添加命名空间引用
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HPSF;
using NPOI.XSSF.UserModel;
(5)读取excel文件
private bool ConstructData(string fileName)
{
//创建workbook
IWorkbook workbook;
FileStream fs = null;
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
string fileExt = Path.GetExtension(fileName).ToLower();
if (fileExt == ".xlsx")
workbook = new XSSFWorkbook(fs);
else if (fileExt == ".xls")
workbook = new HSSFWorkbook(fs);
else
{
workbook = null;
return false;
}
//获得第一张sheet
ISheet sheet = workbook.GetSheetAt(0);
if (sheet == null)
return false;
//最后一列的标号
var rowCount = sheet.LastRowNum;
data.Clear();
List<string> lastCells = new List<string>(new string[10]);
for (var i = 1; i <= rowCount; ++i)
{
var row = sheet.GetRow(i);
//没有数据的行默认是null
if (row == null) continue;
List<string> lst = new List<string>();
for(int k=0;k<10;++k)
{
ICell cell= row.GetCell(k);
if (cell != null)
{
string cellValue = cell.ToString();
lst.Add(cellValue);
lastCells[k] = cellValue;
}
else
{
lst.Add("");
}
}
data.Add(lst);
}
return true;
}
(6)其他的方法请百度。