引入:

using System;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel; namespace NPOIOprateExcel
{
    public class ExcelUtility
    {
        /// <summary>
        /// 将excel导入到datatable
        /// </summary>
        /// <param name="filePath">excel路径</param>
        /// <param name="isColumnName">第一行是否是列名</param>
        /// <returns>返回datatable</returns>
        public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
        {
            DataTable dataTable = null;
            FileStream fs = null;
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            try
            {
                using (fs = File.OpenRead(filePath))
                {
                    // 2007版本
                    if (filePath.IndexOf(".xlsx") > 0)
                        workbook = new XSSFWorkbook(fs);
                    // 2003版本
                    else if (filePath.IndexOf(".xls") > 0)
                        workbook = new HSSFWorkbook(fs);                     if (workbook != null)
                    {
                        sheet = workbook.GetSheetAt(0);//读取第一个sheet,也能循环读取每个sheet
                        dataTable = new DataTable();
                        if (sheet != null)
                        {
                            int rowCount = sheet.LastRowNum+1;//+1 包括列名的行,总行数
                            if (rowCount > 0)
                            {
                                IRow firstRow = sheet.GetRow(0);//第一行
                                int cellCount = firstRow.LastCellNum;//列数                                 //构建datatable的列
                                if (isColumnName)
                                {
                                    startRow = 0;//要读取列名则=0 否则=1
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        cell = firstRow.GetCell(i);
                                        if (cell != null)
                                        {
                                            if (cell.StringCellValue != null)
                                            {
                                                column = new DataColumn(cell.StringCellValue);
                                                dataTable.Columns.Add(column);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        column = new DataColumn("column" + (i + 1));
                                        dataTable.Columns.Add(column);
                                    }
                                }                                 //填充行
                                for (int i = startRow; i < rowCount; ++i) //要读取列名则i<rowCount 否则i <= rowCount
                                {
                                    row = sheet.GetRow(i);
                                    if (row == null) continue;                                     dataRow = dataTable.NewRow();
                                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                                    {
                                        cell = row.GetCell(j);
                                        if (cell == null)
                                        {
                                            dataRow[j] = "";
                                        }
                                        else
                                        {
                                            //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                            switch (cell.CellType)
                                            {
                                                case CellType.Blank:
                                                    dataRow[j] = "";
                                                    break;
                                                case CellType.Numeric:
                                                    short format = cell.CellStyle.DataFormat;
                                                    //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
                                                    if (format == 14 || format == 31 || format == 57 || format == 58)
                                                        dataRow[j] = cell.DateCellValue;
                                                    else
                                                        dataRow[j] = cell.NumericCellValue;
                                                    break;
                                                case CellType.String:
                                                    dataRow[j] = cell.StringCellValue;
                                                    break;
                                            }
                                        }
                                    }
                                    dataTable.Rows.Add(dataRow);
                                }
                            }
                        }
                    }
                }
                return dataTable;
            }
            catch (Exception)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return null;
            }
        }
    }
}

ASP.NET MVC - NPOI读取Excel的更多相关文章

  1. asp.net 使用NPOI读取excel文件

    asp.net 使用NPOI读取excel文件内容 NPOI下载地址:NPOI public class ExcelHelper { /// <summary> /// 读取Excel文件 ...

  2. ASP.NET MVC NPOI导入Excel DataTable批量导入到数据库

    使用NPOI导入Excel 首先在MVC项目中导入NPOI 查询NPOI安装,排序依据,选择:最高下载量,选择第一个. 在控制器中创建ExcelController 在Index视图中写入代码: @u ...

  3. asp.net mvc Dateset读取Excel数据

    //处理Excel //读取Excel [NonAction] public static DataSet ExcelToDS(string Path) { //根据情况选择合适的连接字符,参考msd ...

  4. asp.net MVC NPOI导出excel通用

    一.创建一个类文件添加 public class ExportToExcelColumn { public ExportToExcelColumn(string _Columnnames, strin ...

  5. asp.net mvc NPOI 生成Excel文件

    private string PushToDown(string addtime) { DataTable dt = _bCreateCode.PushtoExcel(addtime); //1.实例 ...

  6. Asp.net MVC NPOI导出Excel

    public class NpoiMemoryStream : MemoryStream { public NpoiMemoryStream() { AllowClose = true; } publ ...

  7. .NET Core 使用NPOI读取Excel返回泛型List集合

    我是一名 ASP.NET 程序员,专注于 B/S 项目开发.累计文章阅读量超过一千万,我的博客主页地址:https://www.itsvse.com/blog_xzz.html 网上有很多关于npoi ...

  8. NPOI读取Excel帮助类,支持xls与xlsx,实现公式解析,空行的处理

    NPOI读取Excel(2003或者2010)返回DataTable.支持公式解析,空行处理. /// <summary>读取excel /// 默认第一行为表头 /// </sum ...

  9. NPOI读取Excel表格类

    public class NPOIHelper    {        private HSSFWorkbook workbook;        public static IWorkbook Lo ...

随机推荐

  1. JQERY EasyUI Tabs 选项卡 自适应浏览器宽度高度 解决方案

    <script type="text/javascript"> $(window).resize(function () { $('#tt').tabs({ width ...

  2. Vue(基础七)_webpack(CommonsChunkPlug的使用)

    ---恢复内容开始--- 一.前言 1.多入口文件配置                               2.CommonsChunkPlugin的用法                   ...

  3. RJ45连接器

    http://www.huilyn.com/path315.html      HBJ-6308ANLF http://www.hanrun.com/en/           HR971169C h ...

  4. Zookeeper 集群安装配置

    今天,栈长分享下 Zookeeper 的集群安装及配置. 下载 下载地址:http://zookeeper.apache.org/ 下载过程就不说了,我们下载了最新的zookeeper-3.4.11. ...

  5. qml: 软件启用前插入广告;

    一般来说,免费软件或者部分商业软件在发布前都会放一些广告在软件上. 下面是我自己的方案(哪位有更好的方案,请告知,先谢): ...... ApplicationWindow{ visible: !ad ...

  6. mysql常用快速查询修改操作

    mysql常用快速查询修改操作 一.查找并修改非innodb引擎为innodb引擎 # 通用操作 mysql> select concat('alter table ',table_schema ...

  7. KVM安装启动虚拟机

    KVM定制OpenStack云主机 如何定制化OpenStack云主机?从去年10月份刚开始接触OpenStack,到现在也有一年了.虽说目前只是停留在用它,对它的一些组件简单的了解,但谈到制作出一个 ...

  8. python操作execl学习笔记(一)

    本节只记录关于execl的读操作: execl 内容及格式 python3 #!/usr/bin/env python #-*- coding:utf-8 -*- import xlrd import ...

  9. android studio导出apk

    在android studio导出的apk分为4种,一种是未签名调试版apk,一种是未签名发行版apk,一种是已签名调试版apk,还有一种是已签名发行版apk.以下将介绍这4种apk如何导出. 一.调 ...

  10. java项目反编译获得源码

    经常能找到一些 过时的 项目源码,但是还是有研究价值的.但是肯定是不会给你源码的. 下面介绍怎么反编译: 1.在项目中找到classes这个文件夹,这个就是编译过的文件. 2.下载反编译工具JD-GU ...