Excel2003:

    #region Excel2003
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xls)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLS(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
XLS.HSSFWorkbook hssfworkbook = new XLS.HSSFWorkbook(fs);
ISheet sheet = hssfworkbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLS(header.GetCell(i) as XLS.HSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
//continue;
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLS(sheet.GetRow(i).GetCell(j) as XLS.HSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 将DataTable数据导出到Excel文件中(xls)
/// </summary>
/// <param name="dt"></param>
/// <param name="file"></param>
public static void TableToExcelForXLS(DataTable dt, string file)
{
XLS.HSSFWorkbook hssfworkbook = new XLS.HSSFWorkbook();
ISheet sheet = hssfworkbook.CreateSheet("Test"); //表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
hssfworkbook.Write(stream);
var buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
} /// <summary>
/// 获取单元格类型(xls)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLS(XLS.HSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.BLANK: //BLANK:
return null;
case CellType.BOOLEAN: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.NUMERIC: //NUMERIC:
return cell.NumericCellValue;
case CellType.STRING: //STRING:
return cell.StringCellValue;
case CellType.ERROR: //ERROR:
return cell.ErrorCellValue;
case CellType.FORMULA: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
#endregion

Excel2007:

    #region Excel2007
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xlsx)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLSX(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
ISheet sheet = xssfworkbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
//continue;
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 将DataTable数据导出到Excel文件中(xlsx)
/// </summary>
/// <param name="dt"></param>
/// <param name="file"></param>
public static void TableToExcelForXLSX(DataTable dt, string file)
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook();
ISheet sheet = xssfworkbook.CreateSheet("Test"); //表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
xssfworkbook.Write(stream);
var buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
} /// <summary>
/// 获取单元格类型(xlsx)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLSX(XSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.BLANK: //BLANK:
return null;
case CellType.BOOLEAN: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.NUMERIC: //NUMERIC:
return cell.NumericCellValue;
case CellType.STRING: //STRING:
return cell.StringCellValue;
case CellType.ERROR: //ERROR:
return cell.ErrorCellValue;
case CellType.FORMULA: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}

注意:操作Excel2003与操作Excel2007使用的是不同的命名空间下的内容

使用NPOI.HSSF.UserModel空间下的HSSFWorkbook操作Excel2003

使用NPOI.XSSF.UserModel空间下的XSSFWorkbook操作Excel2007

        /// <summary>
/// 写入到文件 IWorkbook 接口实现
/// </summary>
/// <param name="book"></param>
/// <param name="fileName"></param>
/// <returns></returns>
private bool WriteToFile(IWorkbook book, string fileName)
{
bool result = true;
try
{
using (MemoryStream ms = new MemoryStream())
{
string filePath = Path.GetDirectoryName(fileName);
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
book.Write(ms);
//保存为Excel文件
var buf = ms.ToArray();
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
}
}
catch (Exception e)
{
LogHelper.WriteErrorLog(e.Message, e);
result = false;
}
finally
{
GC.Collect();
}
return result;
}

在C#中使用NPOI2.0操作Excel2003和Excel2007的更多相关文章

  1. 高抛低吸T+0操作要领(目前行情短线炒作的必备技能)

    最近的行情只能用操蛋来形容,但是危机中不乏机会.现在已经不是之前行情的思路,那着一个股票长线抱着,即使是好的牛股,也经不起目前行情的这 么折腾.所以,现在最适合的操作方式就是高抛低吸.今天低吸保不准明 ...

  2. 使用.NET 4.0+ 操作64位系统中的注册表

    一.64位系统中的注册表 以 LocalMachine 中的启动项为例: 64位应用的注册表位置还是在: SOFTWARE\Microsoft\Windows\CurrentVersion\Run 而 ...

  3. C++中的memset、zeroMemory和={0}操作( 转)

    使用C/C++编程时,常使用ZeroMemory.memset或 “={0}”来对结构体对象进行初始化或清零.然而这三种方式都有各自的特点,使用时需谨慎,否则容易出现严重错误,本人今日解决一个导致宕机 ...

  4. EF5.0中的跨数据库操作

    以前在用MVC + EF 的项目中,都是一个数据库,一个DbContext,因此一直没有考虑过在MVC+EF的环境下对于多个数据库的操作问题.等到要使用时,才发现这个问题也不小(关键是有个坑).直接说 ...

  5. JavaScript jQuery 中定义数组与操作及jquery数组操作

    首先给大家介绍javascript jquery中定义数组与操作的相关知识,具体内容如下所示: 1.认识数组 数组就是某类数据的集合,数据类型可以是整型.字符串.甚至是对象Javascript不支持多 ...

  6. JavaScript中常见的数组操作函数及用法

    JavaScript中常见的数组操作函数及用法 昨天写了个帖子,汇总了下常见的JavaScript中的字符串操作函数及用法.今天正好有时间,也去把JavaScript中常见的数组操作函数及用法总结一下 ...

  7. JavaScript中常见的字符串操作函数及用法

    JavaScript中常见的字符串操作函数及用法 最近几次参加前端实习生招聘的笔试,发现很多笔试题都会考到字符串的处理,比方说去哪儿网笔试题.淘宝的笔试题等.如果你经常参加笔试或者也是一个过来人,相信 ...

  8. jquery中$("#afui").get(0)为什么要加get(0)呢?

    jquery中$("#afui").get(0)为什么要加get(0)呢? 2015-04-13 17:46SYYZZ3 | 浏览 509 次  Jquery $("#a ...

  9. C/C++ 中长度为0的数组

    参考文献:http://blog.csdn.net/zhaqiwen/article/details/7904515 近日在看项目中的框架代码时,发现了了一个奇特的语法:长度为0的数组例如 uint8 ...

随机推荐

  1. POJ 2653 Pick-up sticks(判断线段相交)

    Pick-up sticks Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 7699   Accepted: 2843 De ...

  2. USB枚举过程(2)

    用bus hound 得到的数据 GET MAX LUN 命令 详见USB_MSC_BlukOnly_v1.0 接下来用到的是UFI  SCSI

  3. jquery的clone方法bug的修复

    最近发现jquery的clone的bug,textarea和select的jquery的clone方法有问题,textarea和select的值clone的时候会丢掉,在网上发现一个插件,下载地址如下 ...

  4. PetaPoco T4模板修改生成实体

    PetaPoco T4 模板生成的实体类全部包含再一个.CS文件中.通过修改PetaPoco的T4模板,生成单文件实体. 1.生成单CS文件模板: SigleFile.ttinclude <#@ ...

  5. 无责任Windows Azure SDK .NET开发入门篇三[使用Azure AD 管理用户信息--3.2 Create创建用户]

    3.2 Create创建用户 [HttpPost, Authorize] public async Task<ActionResult> Create( [Bind(Include = & ...

  6. [转][IIS]发布网站,提示用户 'IIS APPPOOL\***' 登录失败。

    链接:http://www.cnblogs.com/tianguook/p/3881075.html 用户 'IIS APPPOOL\DefaultAppPool' 登录失败. 我在windows8中 ...

  7. KMP算法初探

    [edit by xingoo] kmp算法其实就是一种改进的字符串匹配算法.复杂度可以达到O(n+m),n是参考字符串长度,m是匹配字符串长度. 传统的算法,就是匹配字符串与参考字符串挨个比较,如果 ...

  8. jquery 更换皮肤

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. xiaoxia的vim配置

    这样已经很强大了 set nu sts=4 ts=4 sw=4 et si ai set ruler set hlsearch syntax on filetype plugin on

  10. 内​存​泄​露​调​试​之​ ​v​i​s​u​a​l​ ​l​e​a​k​ ​d​e​t​e​c​t​o​r​ ​工​具【转】

    本文参考此文:http://kangzj.net/visual-leak-detector-download/  另外一种检查内存泄露的工具:visual leak  detector  简称  vl ...