(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)其他的方法請百度。