用Nopi做Excel导入导出已经是老生长谈了吧,网上也应有很多类似的文章,今天写这篇文章呢,是用来简单谈下个人在使用Nopi的感受,Nopi导入和导出要做的验证还是很多的,虽然没有拿来做报表,目前的技术水平也还没有到做报表的能力。那么接下来我们分析一下Nopi导入和导出需要使用的东西吧,不过在使用excel之前最好有一定的文件流理念,需要明白流文件。
在说导入导出之前,先引入Nopi组件和IO流:
“`
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System.IO;
//这些并非全部需要,只是笔者在整理一个很全的Excel包括多种格式的才需要
官方网站:http://npoi.codeplex.com/可以下载Nopi组件
然后开始做导入:
可以先做一个帮助类:
```
public static class ExcelHelper
{
/// <summary>
/// 获取单元格的值
/// </summary>
/// <param name="sheet">Excel sheet表名称</param>
/// <param name="rowIndex">行索引</param>
/// <param name="cellIndex">列索引</param>
/// <returns>行索引和列索引从0开始</returns>
///这个方法是用来检查如果你不知道你的单元格里的值是什么类型的就可以用这个方法检查
///返回的字符串代表了单元格内容的值类型
public static string GetCellValue(this ISheet sheet, int rowIndex, int cellIndex)
{
string returnValue = string.Empty;
//拼接的条件
if (sheet != null)
{
//如果当前的sheet不等于空 则获取索引行的值
var row = sheet.GetRow(rowIndex);
if (row != null)
{
//如果行内容不为空 则获取列
var cell = row.GetCell(cellIndex);
if (cell != null)
{
//列也不为空则判断列中的值的类型
switch (cell.CellType)
{
//如果为string类型,则返回String类型
case CellType.String:
returnValue = cell.StringCellValue;
break;
//如果是数字类类型
case CellType.Numeric:
//判断是否为日期类型
if (DateUtil.IsCellDateFormatted(cell))
{
//是日期类型则转化成日期输出
returnValue = DateTime.FromOADate(cell.NumericCellValue).ToString();
}
else
{
//输出数字类型
returnValue = Convert.ToDouble(cell.NumericCellValue).ToString();
}
break;
//是否是bool类型
case CellType.Boolean:
returnValue = Convert.ToString(cell.BooleanCellValue);
break;
//错误函数类型
case CellType.Error:
returnValue = ErrorEval.GetText(cell.ErrorCellValue);
break;
case CellType.Formula:
switch (cell.CachedFormulaResultType)
{
case CellType.String:
string strFORMULA = cell.StringCellValue;
if (strFORMULA != null && strFORMULA.Length > 0)
{
returnValue = strFORMULA.ToString();
}
break;
case CellType.Numeric:
returnValue = Convert.ToString(cell.NumericCellValue);
break;
case CellType.Boolean:
returnValue = Convert.ToString(cell.BooleanCellValue);
break;
case CellType.Error:
returnValue = ErrorEval.GetText(cell.ErrorCellValue);
break;
default:
break;
}
break;
default:
break;
}
}
}
}
return returnValue.Trim();
}
/// <summary>
/// Excel导入
/// </summary>
/// <typeparam name="T">这个方法是将Excle转化成泛型导入</typeparam>
/// <param name="columns">数组形式 列头</param>
/// <param name="excelStream">文件流</param>
/// <param name="excelType">文件类型</param>
/// <returns>这是Excel导