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) ...
随机推荐
- Node.js中环境变量process.env详解
Node.js中环境变量process.env详解process | Node.js API 文档http://nodejs.cn/api/process.html官方解释:process 对象是一个 ...
- 移植并修改成功的模拟iic读写EEPROM at24c02
2010-04-24 12:58:00 注:如果要读24c128或264,地址位为16位的.现在的地址位为8位. protues仿真图 源程序如下: #include <iom16v.h> ...
- Codeforce 296A - Yaroslav and Permutations
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring a ...
- this和构造器的内存分析(***)
this的含义: 1.区分成员变量和局部变量: 2.谁调用这个this就指向谁: public class Person{ private String name; private int age; ...
- ansible中的playbook详解
首先简单说明一下playbook,playbook是什么呢?根本上说playbook和shell脚本没有任何的区别,playbook就像shell一样,也是把一堆的命令组合起来,然后加入对应条件判断等 ...
- django中模型详解-字段类型与约束条件
这片博文来详细说明django模型的使用,涉及到django模型的创建,字段介绍,以及django模型的crud操作,以及一对一等操作. 在使用模型之前,我们首先设置数据库选项,django的默认数据 ...
- url去重 --布隆过滤器 bloom filter原理及python实现
https://blog.csdn.net/a1368783069/article/details/52137417 # -*- encoding: utf-8 -*- ""&qu ...
- Python爬虫(三)——对豆瓣图书各模块评论数与评分图形化分析
文化 经管 ....略 结论: 一个模块的评分与评论数相关,评分为 [8.8——9.2] 之间的书籍评论数往往是模块中最多的
- python3 独立环境 virtualenv & conda
python3 独立环境 virtualenv & conda virtualenv 创建独立python环境 virtualenv env_name -p /usr/bin/python3 ...
- Python语言知识总结
1. 环境 1.1 Anaconda 抛弃python原生安装方式吧,使用Anaconda才是最省心的. 1.2 Miniconda Anaconda 太大了,Miniconda才是王道!下载链接:h ...