//首先Nuget安装NPOI库

using System;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; public static class ExcelExtensions
{
/// <summary>
/// DataSet数据导出到Excel文件
/// </summary>
/// <param name="ds">DataSet</param>
/// <param name="fileName">文件全名</param>
/// <returns></returns>
public static bool DataSetToExcel(DataSet ds, string fileName)
{
IWorkbook workbook = new HSSFWorkbook();
FileStream fs = null;
try
{
int k = 0;
foreach (DataTable dt in ds.Tables)
{
if (dt != null && dt.Rows.Count > 0)
{
ISheet sheet = null;
if (!string.IsNullOrWhiteSpace(dt.TableName))
{
sheet = workbook.CreateSheet(dt.TableName);//创建一个名称为Sheet0的表
}
else
{
sheet = workbook.CreateSheet("Sheet" + k.ToString());//创建一个名称为Sheet0的表
}
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数 //设置列头
IRow row = sheet.CreateRow(0);//excel第一行设为列头
ICell cell = null;
for (int c = 0; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
} //设置每行每列的单元格,
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i + 1);
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);//excel第二行开始写入数据
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
//设置最后一列单元格宽度
sheet.SetColumnWidth(columnCount - 1, 20000);
k = k + 1;
}
}
using (fs = File.OpenWrite(fileName))
{
workbook.Write(fs);//向打开的这个xls文件中写入数据
}
return true;
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
return false;
}
} /// <summary>
/// 将excel导入到dataset
/// </summary>
/// <param name="filePath">excel路径</param>
/// <param name="isColumnName">第一行是否是列名</param>
/// <returns>返回datatable</returns>
public static DataSet ExcelToDataSet(string filePath, bool isColumnName)
{
DataSet dataset = new DataSet();
DataTable dataTable = null;
FileStream fs = null;
IWorkbook workbook = null;
int startRow = 0;
try
{
using (fs = File.OpenRead(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > 0)
workbook = new HSSFWorkbook(fs); if (workbook != null)
{
for (int n = 0; n < workbook.NumberOfSheets; n++)
{
ISheet sheet = workbook.GetSheetAt(n); //读取第一个sheet,当然也可以循环读取每个sheet
dataTable = new DataTable();
if (sheet != null && sheet.SheetName != "")
{
dataTable.TableName = sheet.SheetName;
int rowCount = sheet.LastRowNum; //总行数
if (rowCount > 0)
{
IRow firstRow = sheet.GetRow(0); //第一行
int cellCount = firstRow.LastCellNum; //列数 //构建datatable的列
DataColumn column = null;
ICell cell = null;
if (isColumnName)
{
startRow = 1; //如果第一行是列名,则从第二行开始读取
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 + 1));
dataTable.Columns.Add(column);
}
} //填充行
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null || string.IsNullOrWhiteSpace(row.Cells[0].ToString()))
continue; DataRow 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 == 14 || format == 31 || format == 57
|| format == 58)
dataRow[j] = cell.DateCellValue;
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
}
}
dataset.Tables.Add(dataTable);
}
}
}
return dataset;
}
catch (Exception)
{
if (fs != null)
{
fs.Close();
}
return null;
}
}
}

  

NPOI库读写Excel文件的更多相关文章

  1. C# 使用 NPOI 库读写 Excel 文件

    NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件.在处理Excel文件上,NPOI 可以同时兼容 xls 和 xlsx.官网提供了一份 Examples,给出 ...

  2. C# 使用 NPOI 库读写 Excel 文件(转载)

    NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件.在处理Excel文件上,NPOI 可以同时兼 容xls 和 xlsx.官网提供了一份Examples,给出了 ...

  3. C# 中 NPOI 库读写 Excel 文件的方法【摘】

    原作:淡水网志 NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件.在处理Excel文件上,NPOI 可以同时兼容 xls 和 xlsx.官网提供了一份 Exa ...

  4. MFC vs2012 Office2013 读写excel文件

    近期在忙一个小项目(和同学一起搞的),在这里客户要求不但读写txt,而且可以读写excel文件,这里本以为很简单,结果...废话少说,过程如下: 笔者环境:win7 64+VS2012+Office2 ...

  5. python 读写 Excel文件

    最近用python处理一个小项目,其中涉及到对excel的读写操作,通过查资料及实践做了一下总结,以便以后用. python读写excel文件要用到两个库:xlrd和xlwt,首先下载安装这两个库. ...

  6. C++读写EXCEL文件OLE,java读写excel文件POI 对比

    C++读写EXCEL文件方式比较 有些朋友问代码的问题,将OLE读写的代码分享在这个地方,大家请自己看.http://www.cnblogs.com/destim/p/5476915.html C++ ...

  7. Python使用openpyxl读写excel文件

    Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...

  8. Python使用读写excel文件

    Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...

  9. 【转发】Python使用openpyxl读写excel文件

    Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...

随机推荐

  1. 痞子衡嵌入式:改动i.MXRT1xxx里IOMUXC_GPR寄存器保留位可能会造成系统异常

    大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是改动i.MXRT1xxx里IOMUXC_GPR寄存器保留位可能会造成系统异常. 痞子衡的嵌入式技术交流群里有一位非常活跃的朋友(网名:文 ...

  2. Ajax|看这一篇就够了!详解Ajax工作原理及开发步骤

    传统开发的缺点,是对于浏览器的页面,全部都是全局刷新的体验.如果我们只是想取得或是更新页面中的部分信息那么就必须要应用到局部刷新的技术. 局部刷新也是有效提升用户体验的一种非常重要的方式. Ajax技 ...

  3. Scrapy中的错误

    TabError: Inconsistent use of tabs and spaces in indentation 需要将  .py  文件中的使用 tab 做的空格符删掉,打成空格符.任何一个 ...

  4. 使用shell脚本循环处理文本

    公司是使用puppet来进行配置管理, 某天修改完puppet后领导回复: 我们有一个文档cabinet.txt记录了物理机器所在的机柜, 除了文档里的其他机器都是虚拟机或云服务器, 对虚拟机的pup ...

  5. Redis(二) 数据类型操作指令以及对应的RedisTemplate方法

    1.Redis key值操作以及RedisTemplate对应的API 本文默认使用RedisTemplate,关于RedisTemplate和StringRedisTemplate的区别如下 Red ...

  6. Ascend Pytorch算子适配层开发

    Ascend Pytorch算子适配层开发 适配方法 找到和PyTorch算子功能对应的NPU TBE算子,根据算子功能计算出输出Tensor的size,再根据TBE算子原型构造对应的input/ou ...

  7. springmvc——mvc:annotation-driven标签的作用

  8. [翻译]Go与C#的比较,第二篇:垃圾回收

    Go vs C#, part 2: Garbage Collection | by Alex Yakunin | ServiceTitan - Titan Tech | Medium 目录 译者注 什 ...

  9. 面试官:MySQL的可重复读级别能解决幻读问题吗?

    引言 之前在深入了解数据库理论的时候,了解到事务的不同隔离级别可能存在的问题.为了更好的理解所以在MySQL数据库中测试复现这些问题.关于脏读和不可重复读在相应的隔离级别下都很容易的复现了. 但是对于 ...

  10. NOIP模拟测试26「嚎叫响彻在贪婪的机房·主仆见证了 Hobo 的离别·征途堆积出友情的永恒」

    题目比较神仙,注意是题目神仙 贪婪暗示贪心,堆积暗示堆优化$\%\%\%\%\%\%\%$ 两个乱搞$+$一个堆优化$dp$ 嚎叫响彻在贪婪的机房 题解 对于一个序列来说只要他们差的$gcd$不为$1 ...