c# Excel数据导入

  • 引用
    引用DLL

  • 读取文档

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Text.RegularExpressions;

IWorkbook workbook;//XSSF  和 HSSF 都继承接口IWorkBook
ISheet sheet; //sheet页
IRow header;  //一行
ICell cell;   //一个单元格

 //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
if (fileExt == ".xlsx")
{ 
    workbook = new XSSFWorkbook(fs); 
} 
else if (fileExt == ".xls") 
{ 
    workbook = new HSSFWorkbook(fs); 
}
 else 
{ 
return Json(new FeedbackModel { Result = false, MsgCode = "文档错误!" }, 
  JsonRequestBehavior.AllowGet);
}

sheet = workbook.GetSheetAt(0);
cell = sheet.GetRow(i).GetCell(j);		
  • 判断数据类型并返回值
public object GetValueType(ICell cell)
{
    object value = null;
    try
    {
        if (cell.CellType != CellType.Blank)
        {
            switch (cell.CellType)
            {
                case CellType.Numeric:
                    // Date comes here
                    if (DateUtil.IsCellDateFormatted(cell))
                    {
                        value = cell.DateCellValue;
                    }
                    else
                    {
                        // Numeric type
                        value = cell.NumericCellValue;
                    }
                    break;
                case CellType.Boolean:
                    // Boolean type
                    value = cell.BooleanCellValue;
                    break;
                case CellType.Formula:
                    value = cell.CellFormula;
                    break;
                default:
                    // String type
                    value = cell.StringCellValue;
                    break;
            }
        }
    }
    catch (Exception)
    {
        value = "";
    }
    return value;
}
发布了241 篇原创文章 · 获赞 14 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_29150765/article/details/85159878