NPOI 导入Excel和读取Excel
1、整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet;行:Row;单元格Cell。
2、NPOI是POI的C#版本,NPOI的行和列的index都是从0开始
3、POI读取Excel有两种格式一个是HSSF,另一个是XSSF。 HSSF和XSSF的区别如下:
HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format.
XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
即:HSSF适用2007以前的版本,XSSF适用2007版本及其以上的。
下面是用NPOI读写Excel的例子:ExcelHelper封装的功能主要是把DataTable中数据写入到Excel中,或者是从Excel读取数据到一个DataTable中。
ExcelHelper类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Data; namespace NetUtilityLib
{
public class ExcelHelper : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed; public ExcelHelper(string fileName)
{
this.fileName = fileName;
disposed = false;
} /// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name="data">要导入的数据</param>
/// <param name="isColumnWritten">DataTable的列名是否要导入</param>
/// <param name="sheetName">要导入的excel的sheet的名称</param>
/// <returns>导入数据行数(包含列名那一行)</returns>
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = ;
int j = ;
int count = ;
ISheet sheet = null; fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > ) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > ) // 2003版本
workbook = new HSSFWorkbook(); try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -;
} if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow();
for (j = ; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = ;
}
else
{
count = ;
} for (i = ; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = ; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs); //写入到excel
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -;
}
} /// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = ;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > ) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > ) // 2003版本
workbook = new HSSFWorkbook(fs); if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt();
}
}
else
{
sheet = workbook.GetSheetAt();
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow();
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + ;
}
else
{
startRow = sheet.FirstRowNum;
} //最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
} return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
} public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
} protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
} fs = null;
disposed = true;
}
}
}
}
补充个方法
/// <summary>
/// 获取单元格的值(读取异常的时候调用)
/// </summary>
/// <param name="Cell"></param>
/// <returns></returns>
private object GetCellValue(ICell Cell)
{
object value = null;
try
{
switch (Cell.CellType)
{
case CellType.Blank:
value = Cell.StringCellValue;
break;
case CellType.String:
value = Cell.StringCellValue;
break;
case CellType.Numeric:
value = Cell.NumericCellValue.ToString();
break;
case CellType.Boolean:
value = Cell.BooleanCellValue;
break;
case CellType.Formula:
value = Cell.RichStringCellValue;
break;
case CellType.Error:
value = Cell.ErrorCellValue;
break;
case CellType.Unknown:
value = Cell.ToString();
break; }
}
catch (Exception)
{
value = System.DBNull.Value;
}
return value;
}
测试代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data; namespace NPOIExcelExample
{
class Program
{
static DataTable GenerateData()
{
DataTable data = new DataTable();
for (int i = ; i < ; ++i)
{
data.Columns.Add("Columns_" + i.ToString(), typeof(string));
} for (int i = ; i < ; ++i)
{
DataRow row = data.NewRow();
row["Columns_0"] = "item0_" + i.ToString();
row["Columns_1"] = "item1_" + i.ToString();
row["Columns_2"] = "item2_" + i.ToString();
row["Columns_3"] = "item3_" + i.ToString();
row["Columns_4"] = "item4_" + i.ToString();
data.Rows.Add(row);
}
return data;
} static void PrintData(DataTable data)
{
if (data == null) return;
for (int i = ; i < data.Rows.Count; ++i)
{
for (int j = ; j < data.Columns.Count; ++j)
Console.Write("{0} ", data.Rows[i][j]);
Console.Write("\n");
}
} static void TestExcelWrite(string file)
{
try
{
using (ExcelHelper excelHelper = new ExcelHelper(file))
{
DataTable data = GenerateData();
int count = excelHelper.DataTableToExcel(data, "MySheet", true);
if (count > )
Console.WriteLine("Number of imported data is {0} ", count);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
} static void TestExcelRead(string file)
{
try
{
using (ExcelHelper excelHelper = new ExcelHelper(file))
{
DataTable dt = excelHelper.ExcelToDataTable("MySheet", true);
PrintData(dt);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
} static void Main(string[] args)
{
string file = "..\\..\\myTest.xlsx";
TestExcelWrite(file);
TestExcelRead(file);
}
}
}
补充调用方法:
HttpPostedFileBase excelFile = Request.Files["fileName"]; //取到上传域
if (null != excelFile)
{
string fileName = Path.GetFileName(excelFile.FileName); //取到文件的名称 excelFile.SaveAs(Server.MapPath("~/Upload/") + System.IO.Path.GetFileName(excelFile.FileName));
string a = Server.MapPath("~/Upload/" + fileName);
ExcelHelper eh = new ExcelHelper(a); if (fileName.Equals("") || null == fileName)
{ //没有选择文件就上传的话,则跳回到上传页面
return false;
}
ExcelHelper eh = new ExcelHelper(a);
参考:http://www.cnblogs.com/luxiaoxun/p/3374992.html
NPOI 导入Excel和读取Excel的更多相关文章
- C#操作Excel文件(读取Excel,写入Excel)
看到论坛里面不断有人提问关于读取excel和导入excel的相关问题.闲暇时间将我所知道的对excel的操作加以总结,如今共享大家,希望给大家可以给大家带了一定的帮助.另外我们还要注意一些简单的问题1 ...
- NPOI操作excel之读取excel数据
NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目. 一.下载引用 去NPOI官网http://npoi.codeplex. ...
- 使用NPOI导入导出标准的Excel
关于NPOI NPOI是POI项目的.NET版本,是由@Tony Qu(http://tonyqus.cnblogs.com/)等大侠基于POI开发的,可以从http://npoi.codeplex. ...
- jxl读写excel, poi读写excel,word, 读取Excel数据到MySQL
这篇blog是介绍: 1. java中的poi技术读取Excel数据,然后保存到MySQL数据中. 2. jxl读写excel 你也可以在 : java的poi技术读取和导入Excel了解到写入Exc ...
- c#操作excel方式三:使用Microsoft.Office.Interop.Excel.dll读取Excel文件
1.引用Microsoft.Office.Interop.Excel.dll 2.引用命名空间.使用别名 using System.Reflection; using Excel = Microsof ...
- SpringBoot(十三)_springboot上传Excel并读取excel中的数据
今天工作中,发现同事在整理数据,通过excel上传到数据库.所以现在写了篇利用springboot读取excel中的数据的demo.至于数据的进一步处理,大家肯定有不同的应用场景,自行修改 pom文件 ...
- POI导入excel时读取excel数据的真实行数
有很多时候会出现空的数据导致行数被识别多的情况 // 获取Excel表的真实行数 int getExcelRealRow(Sheet sheet) { boolean flag = false; fo ...
- NPOI 导入为table 处理excel 格式问题
ICell cell = row.GetCell(j); if (!cell.isDbNullOrNull()) { switch (cell.CellType) { case CellType.Bl ...
- NPOI读取Excel,导入数据到Excel练习01
NPOI 2.2.0.0,初级读取导入Excel 1.读取Excel,将数据绑定到dgv上 private void button1_Click(object sender, EventArgs e) ...
随机推荐
- 转:【专题九】实现类似QQ的即时通信程序
引言: 前面专题中介绍了UDP.TCP和P2P编程,并且通过一些小的示例来让大家更好的理解它们的工作原理以及怎样.Net类库去实现它们的.为了让大家更好的理解我们平常中常见的软件QQ的工作原理,所以在 ...
- navicat链接阿里云mysql报80070007: SSH Tunnel: Server does not support diffie-hellman-group1-sha1 for keyexchange
http://www.jianshu.com/p/200572ed066c navicat 链接数据库 使用navicat 的ssh通道连接数据库回遇到权限问题 错误代码如下: 80070007: ...
- 加密对象到locastorage / 从 locastorage解密对象
var obj={name:"致远",age:21,address:"江西上饶XXXX",hobby:"看书,编程"};//用中文 记得加e ...
- (Linux)动态度的编写
动态库*.so在linux下用c和c++编程时经常会碰到,最近在网站找了几篇文章介绍动态库的编译和链接,总算搞懂了这个之前一直不太了解得东东,这里做个笔记,也为其它正为动态库链接库而苦恼的兄弟们提供一 ...
- POJ 1308 Is It A Tree?和HDU 1272 小希的迷宫
POJ题目网址:http://poj.org/problem?id=1308 HDU题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=1272 并查集的运用 ...
- LogUtil工具
package com.develop.web.util; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logg ...
- centos7.2 开机启动脚本
vim ~/.bashrc 然后最后一行添加 source /etc/profile 一.添加开机自启服务 在CentOS 7中添加开机自启服务非常方便,只需要两条命令(以Jenkins为例):sys ...
- JS传值中文乱码解决方案
JS传值中文乱码解决方案 一.相关知识 1,Java相关类: (1)java.net.URLDecoder类 HTML格式解码的实用工具类,有一个静态方法:public static String ...
- grep 正则匹配
\{0,n\}:至多n次 \{\ 匹配/etc/passwd文件中数字出现只是数字1次到3次 匹配/etc/grub2.cfg文件以一个空格开头匹配一个字符的文件的所有行 显示以LISTEN结尾的行 ...
- python---01.各类计算机语言,python历史,变量,常量,数据类型,if条件
一.认识计算机 1.硬件组成: CPU(大脑) + 内存(缓冲) + 主板(连接各部分) + 电源(心脏) + 显示器 + 键盘 +鼠标+ 显卡 + 硬盘 2.操作系统 ①windows ...