NPOI 是 POI 项目的 .NET 版本。POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。

 一、下载引用

去NPOI官网http://npoi.codeplex.com/下载需要引用的dll,即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll(office2007版需要此dll)。

二、Excel转datatable类

excel数据:

Excel转datatable类如下:

 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 = ;
try
{
using (fs = File.OpenRead(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > )
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > )
workbook = new HSSFWorkbook(fs); if (workbook != null)
{
sheet = workbook.GetSheetAt();//读取第一个sheet,当然也可以循环读取每个sheet
dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > )
{
IRow firstRow = sheet.GetRow();//第一行
int cellCount = firstRow.LastCellNum;//列数 //构建datatable的列
if (isColumnName)
{
startRow = ;//如果第一行是列名,则从第二行开始读取
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 + ));
dataTable.Columns.Add(column);
}
} //填充行
for (int i = startRow; i <= rowCount; ++i)
{
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 == || format == || format == || format == )
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;
}
}
}
}

三、返回结果

调用上述方法:

private void ReadExcelData()
{
DataTable dataTable = null;//接受从excel读取的数据
string filePath = MapPath("/ExcelFile/excel1.xls");//文件路径姑且写死
dataTable = ExcelUtility.ExcelToDataTable(filePath, true);
}

返回的datatable如下:

以上就是NPOI读取excel的方法,接下来就可以把datatable插入数据库了,此处省略。

NPOI操作excel之读取excel数据的更多相关文章

  1. c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出

    c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出 using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using S ...

  2. C#操作Excel文件(读取Excel,写入Excel)

    看到论坛里面不断有人提问关于读取excel和导入excel的相关问题.闲暇时间将我所知道的对excel的操作加以总结,如今共享大家,希望给大家可以给大家带了一定的帮助.另外我们还要注意一些简单的问题1 ...

  3. NPOI 导入Excel和读取Excel

    1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 ...

  4. jxl读写excel, poi读写excel,word, 读取Excel数据到MySQL

    这篇blog是介绍: 1. java中的poi技术读取Excel数据,然后保存到MySQL数据中. 2. jxl读写excel 你也可以在 : java的poi技术读取和导入Excel了解到写入Exc ...

  5. c#操作excel方式三:使用Microsoft.Office.Interop.Excel.dll读取Excel文件

    1.引用Microsoft.Office.Interop.Excel.dll 2.引用命名空间.使用别名 using System.Reflection; using Excel = Microsof ...

  6. SpringBoot(十三)_springboot上传Excel并读取excel中的数据

    今天工作中,发现同事在整理数据,通过excel上传到数据库.所以现在写了篇利用springboot读取excel中的数据的demo.至于数据的进一步处理,大家肯定有不同的应用场景,自行修改 pom文件 ...

  7. ThinkPHP3.2.3使用PHPExcel类操作excel导入读取excel

    方法一: 1. 下载PHPExcel并保存在如下位置: 2. 在控制器中引用 vendor("PHPExcel.PHPExcel"); $objReader = \PHPExcel ...

  8. POI导入excel时读取excel数据的真实行数

    有很多时候会出现空的数据导致行数被识别多的情况 // 获取Excel表的真实行数 int getExcelRealRow(Sheet sheet) { boolean flag = false; fo ...

  9. NPOI操作excel之写入数据到excel表

    在上一篇<NPOI操作excel之读取excel数据>我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中. using System; u ...

随机推荐

  1. 51nod p1175 区间中第K大的数

    1175 区间中第K大的数 基准时间限制:1 秒 空间限制:131072 KB 分值: 160 难度:6级算法题   一个长度为N的整数序列,编号0 - N - 1.进行Q次查询,查询编号i至j的所有 ...

  2. ural 1142. Relations

    1142. Relations Time limit: 1.0 secondMemory limit: 64 MB Background Consider a specific set of comp ...

  3. [Leetcode] Maximum Gap

    Given an unsorted array, find the maximum difference between the successive elements in its sorted f ...

  4. jS事件:target与currentTarget区别

    target在事件流的目标阶段:currentTarget在事件流的捕获,目标及冒泡阶段.只有当事件流处在目标阶段的时候,两个的指向才是一样的, 而当处于捕获和冒泡阶段的时候,target指向被单击的 ...

  5. [深入浅出WP8.1(Runtime)]应用文件的URI方案

    6.2.4 应用文件的URI方案 在上文我们获取文件的方式都是通过应用程序的三个跟目录的文件夹对象来获取文件夹对象和文件对象,那么我们这一小节来讲解一种新的获取文件对象的方式,这种方式就是通过Uri地 ...

  6. BZOJ 3211 题解

    3211: 花神游历各国 Time Limit: 5 Sec  Memory Limit: 128 MBSubmit: 2549  Solved: 946[Submit][Status][Discus ...

  7. upload控件上传json文件合并的两种方法

    方法一: byte[] byte1 = FileUpload1.FileBytes; byte[] byte2 = FileUpload2.FileBytes; byte[] a1 = Encodin ...

  8. java基础--java静态代码块和静态方法的区别、static用法

    转载自: http://blog.sina.com.cn/s/blog_afddb8ff0101aqs9.html 静态代码块:有些代码必须在项目启动的时候就执行,这种代码是主动执行的(当类被载入时, ...

  9. 建立和断开与MySQL服务器的连接

    MySQL 与 mysql 之间的区别: MySQL指完整的MySQL DBMS系统,mysql仅代表一个特定的客户程序. 连接服务器: >mysql -h host_name -p -u us ...

  10. JAVA代码实现下载单个文件,和下载打包文件

    //下载单个文件调用方法 /**     * response     * imgPath 下载图片地址    * fileName 保存下载文件名称    * @date 2015年4月14日 下午 ...