【转】NPOI读写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 = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; 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 -1;
}
}
/// <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 = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
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 + 1;
}
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;
}
}
}
}
--===================对于Excel模板,向模板中填充数据且保存
using(fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
}
using(fs = new FileStream(fileName, FileMode.Create))
{
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.GetRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs);//写入Excel
}
【转】NPOI读写Excel的更多相关文章
- NPOI读写Excel
1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 ...
- NPOI读写Excel【转载】
参考示例:https://www.cnblogs.com/luxiaoxun/p/3374992.html 感谢! 1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表): ...
- 使用NPOI读写Excel、Word
NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目. 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 ...
- C#使用NPOI读写excel
本帖内容来自网络+自己稍作整理,已找不到原贴,侵删 个人比较习惯用NPOI操作excel,方便易理解.在宇宙第一IDE(笑)——VS2017中插入NPOI就很方便: 首先安装NPOI: 然后在.cs文 ...
- NPOI读写Excel组件封装Excel导入导出组件
后台管理系统多数情况会与Excel打交道,常见的就是Excel的导入导出,对于Excel的操作往往是繁琐且容易出错的,对于后台系统的导入导出交互过程往往是固定的,对于这部分操作,我们可以抽离出公共组件 ...
- NPOI 读写Excel
实例功能概述: 1.支持Excel2003以及2007 2.支持Excel读取到DataTable(TableToExcel) 3.支持DataTable导出到Excel(TableToExcel) ...
- Unity3d 使用NPOI读写Excel 遇到的问题
开发环境:unity5.3 NPOI(.net 2.0版 http://npoi.codeplex.com/) 运行环境:PC版, 其他平台没有测试 先上效果图: 实现步骤: 1.新建一个Exce ...
- C#使用NPOI读写Excel的注意事项
NPOI的基本使用参照:https://www.cnblogs.com/lixiaobin/p/NPOI.html 既存文档读取修改方法 *既存Excel文档修改保存注意使用FileMode.Crea ...
- 用插件NPOI读写excel
1.用插件NPOIusing NPOI.SS.UserModel;using NPOI.XSSF.UserModel;using NPOI.HSSF.UserModel; public class E ...
随机推荐
- MonoDevelop 的一些设置
原地址:http://hi.baidu.com/next2_me MonoDevelop保存跳到顶部 Saving in MonoDevelop goes to the top line. MonoD ...
- Python——标准库 Sys模块
---------------------------------------------------------------------------------------------------- ...
- python抓包截取http记录日志
#!/usr/bin/python import pcap import dpkt import re def main(): pc=pcap.pcap(name="eth1" ...
- 微信小程序bindtap和catchtap区别
bindtap可以产生冒泡事件 catchtap只自身触发事件,不会传递到父视图 文章来源:刘俊涛的博客 地址:http://www.cnblogs.com/lovebing 欢迎关注 ...
- linux下统计程序/函数运行时间(转)
一. 使用time 命令 例如编译一个hello.c文件 #gcc hello.c -o hello 生成了hello可执行文件,此时统计该程序的运行时间便可以使用如下命令 #time ./hello ...
- ios 第三方qq登陆,号码禁止授权
在以下加入測试账号就可以 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYWxpbmNleGlhb2hhbw==/font/5a6L5L2T/fontsiz ...
- 解决WSDL.EXE不能解析外部Import的XSD的问题
今天碰到一个WSDL,比较奇怪,它是用Java生成的. <types> <xsd:schema> <xsd:import namespace="ht ...
- C语言基础(18)-内存
一.内存布局 1.1 代码区 代码区code,程序被操作系统加载到内存的时候,所有的可执行代码都加载到代码区,也叫代码段.代码区是可读不可写的. 代码区中的所有的内容在程序加载到内存的时候就确定了,运 ...
- python-扫描某一网段下的ip
#!/usr/bin/env python #-*- coding:utf-8 -*- ############################ #File Name: ipscaner.py #Au ...
- c++ why doesn't c++ allow rebinding a reference ?
http://stackoverflow.com/questions/27037744/why-doesnt-c-allow-rebinding-a-reference# 1. The primary ...