//首先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. 记一次zabbix-server故障恢复导致的事故 zabbix-server.log -- One child process died

    前言 zabbix-server昨天出了个问题,不停的重启.昨天摆弄到晚上也不搞清楚原因,按照网上说的各种操作,各种CacheSize.TimeOut.StartPollers都改了,还有什么Incl ...

  2. HTML5之WebSocket(转自知乎)

    在认识websocket之前,我们必须了解的是websocket有什么用? 他能解决我们遇到的什么问题? 如果没用,那么我们就么有使用它的必要的. websocket就是建立起全双工协议的,提高了效率 ...

  3. 深度学*点云语义分割:CVPR2019论文阅读

    深度学*点云语义分割:CVPR2019论文阅读 Point Cloud Oversegmentation with Graph-Structured Deep Metric Learning 摘要 本 ...

  4. GStreamer跨平台多媒体框架

    GStreamer跨平台多媒体框架 Gstreamer基本概念 GStreamer是用于构造媒体处理组件图的库.它支持的应用程序范围从简单的Ogg / Vorbis回放,音频/视频流到复杂的音频(混合 ...

  5. Mac设置charles证书信任

  6. 为IHttpClientFactory添加动态命名配置

    某些时候我们需要为HttpClient动态配置一些东西, 例如证书等, 参考博问 如何使用IHttpClientFactory动态添加cer证书. 例如服务是一个回调服务, 而被回调方采用了自定义的h ...

  7. 【读书笔记】《C语言 从入门到精通》(第三版)笔记

    C语言,上学的时候都没学好,没想到现在却靠它吃饭.因为对C语言还是比较熟悉,所以买这本书是用来当"字典"用的.所以下面的笔记不会有很基础的内容. 1.书籍介绍 2.结构体 3.[C ...

  8. centos 7 能ping通但是telnet 22 不通解决方法

    试过关闭Linux防火墙,打开sshd服务,修改ens33为enth0.发现不好使. 经过不断的努力我发现,windows系统里面的VMware Network Adapter VMnet8设置的ip ...

  9. 【模拟7.14】B. 熟练剖分(tree) (概率DP)

    一道概率神题,考试时没读清题考完看了学长的玄学题解看了好几个小时 首先f[i][j]表示在点 i 为根的子树中,向下最长轻链长度小于等于 j 的概率. 首先递归下去并求出子树大小,然后枚举重儿子,枚举 ...

  10. Pytest学习笔记4-assert断言

    前言 pytest作为单元测试框架,自然少不了断言功能,用过unittest的人都知道,在unittest中有丰富的断言方法,比如assertEqual().assertIn().assertTrue ...