C#中NPOI操作excel之读取和写入excel数据
一、下载引用
下载需要引用的dll,即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll(office2007版需要此dll)。
二、excel转datatable类
- using System;
- using System.Data;
- using System.IO;
- using NPOI.SS.UserModel;
- using NPOI.XSSF.UserModel;
- using NPOI.HSSF.UserModel;
- namespace NPOIOprateExcel
- {
- public class ExcelUtility
- {
- /// <summary>
- /// 将excel导入到datatable
- /// </summary>
- /// <param name="filePath">excel路径</param>
- /// <param name="isColumnName">第一行是否是列名</param>
- /// <returns>返回datatable</returns>
- public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
- {
- DataTable dataTable = null;
- FileStream fs = null;
- DataColumn column = null;
- DataRow dataRow = null;
- IWorkbook workbook = null;
- ISheet sheet = null;
- IRow row = null;
- ICell cell = 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)
- {
- sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
- dataTable = new DataTable();
- if (sheet != null)
- {
- int rowCount = sheet.LastRowNum;//总行数
- if (rowCount > 0)
- {
- IRow firstRow = sheet.GetRow(0);//第一行
- int cellCount = firstRow.LastCellNum;//列数
- //构建datatable的列
- 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)
- {
- row = sheet.GetRow(i);
- if (row == null) continue;
- 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);
- }
- }
- }
- }
- }
- return dataTable;
- }
- catch (Exception)
- {
- if (fs != null)
- {
- fs.Close();
- }
- return null;
- }
- }
- }
- }
三、结果
四、写入excel类
- public static bool DataTableToExcel(DataTable dt)
- {
- bool result = false;
- IWorkbook workbook = null;
- FileStream fs = null;
- IRow row = null;
- ISheet sheet = null;
- ICell cell = null;
- try
- {
- if (dt != null && dt.Rows.Count > 0)
- {
- workbook = new HSSFWorkbook();
- sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
- int rowCount = dt.Rows.Count;//行数
- int columnCount = dt.Columns.Count;//列数
- //设置列头
- row = sheet.CreateRow(0);//excel第一行设为列头
- 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());
- }
- }
- using (fs = File.OpenWrite(@"D:/myxls.xls"))
- {
- workbook.Write(fs);//向打开的这个xls文件中写入数据
- result = true;
- }
- }
- return result;
- }
- catch (Exception ex)
- {
- if (fs != null)
- {
- fs.Close();
- }
- return false;
- }
- }
结果如下:
源码地址:http://download.csdn.net/detail/coderk2014/9328779
C#中NPOI操作excel之读取和写入excel数据的更多相关文章
- C#中创建、打开、读取、写入、保存Excel的一般性代码
---转载:http://hi.baidu.com/zhaocbo/item/e840bcf941932d15fe358228 1. Excel对象微软的Excel对象模型包括了128个不同的对象,从 ...
- Java使用POI读取和写入Excel指南
Java使用POI读取和写入Excel指南 做项目时经常有通过程序读取Excel数据,或是创建新的Excel并写入数据的需求: 网上很多经验教程里使用的POI版本都比较老了,一些API在新版里已经废弃 ...
- Java使用POI读取和写入Excel指南(转)
做项目时经常有通过程序读取Excel数据,或是创建新的Excel并写入数据的需求: 网上很多经验教程里使用的POI版本都比较老了,一些API在新版里已经废弃,这里基于最新的Apache POI 4.0 ...
- C#中npoi操作Excel[版本2.0.1读写2003、2007格式]
下载npoi2.0.1dll文件:http://download.csdn.net/detail/pukuimin1226/5851747 public static void test1() ...
- 一个I/O线程可以并发处理N个客户端连接和读写操作 I/O复用模型 基于Buf操作NIO可以读取任意位置的数据 Channel中读取数据到Buffer中或将数据 Buffer 中写入到 Channel 事件驱动消息通知观察者模式
Tomcat那些事儿 https://mp.weixin.qq.com/s?__biz=MzI3MTEwODc5Ng==&mid=2650860016&idx=2&sn=549 ...
- 读取、写入excel数据
在实际项目中,不可避免的会操作excel表格.一直以来都是读取excel表格,可今天为了写入excel表格,可是煞费苦心,终于完成,记录下来以便后续使用. 1.读取excel表格的数据 读取excel ...
- Java 使用Apache POI读取和写入Excel表格
1,引入所用的包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxm ...
- Python3 读取和写入excel
https://blog.csdn.net/weixin_43094965/article/details/82226263一.Excel 1.Excel文件三个对象 workbook: 工作簿,一个 ...
- MATLAB读取和写入Excel文件
1. 读取Excel文件 (a) 命令方式xlsread: 读取命令:[data,text] = xlsread(FileName, SheetName, Range); data保存的是数据单元 ...
随机推荐
- 单例模式全面学习(C++版)
单例模式:用来创建独一无二的,只能够有一个实例的对象. 单例模式的结构是设计模式中最简单的,但是想要完全实现一个线程安全的单例模式还是有很多陷阱的,所以面试的时候属于一个常见的考点~ 单例模式的应用场 ...
- -bash: locate: command not found
部分版本的linux系统使用locate快速查找某文件路径会报以下错误: -bash: locate: command not found 其原因是没有安装mlocate这个包 安装:yum -y ...
- Nodejs express、html5实现拖拽上传
一.前言 文件上传是一个比较常见的功能,传统的选择方式的上传比较麻烦,需要先点击上传按钮,然后再找到文件的路径,然后上传.给用户体验带来很大问题.html5开始支持拖拽上传的需要的api.nodejs ...
- 结对编程2—Fault&Error&Failure
学习进度表 点滴成就 学习时间 新编写代码行数 博客量(篇) 学到知识点 第一周 8 0 0 了解软件工程 第二周 10 0 1 博文一篇 第三周 15 0 2 选择项目.调查问卷 第四周 20 80 ...
- XCache 一种快速可靠的PHP操作码缓存
1,错误报告开启 错误报告是在PHP中一个非常有用的功能,应同时在开发阶段启用. 这可以帮助我们确定我们的代码中的问题. 最常用的功能是“E_ALL”,这有助于我们发现所有的警告和严重错误. 必须指出 ...
- Codeforces 592D - Super M - [树的直径][DFS]
Time limit 2000 ms Memory limit 262144 kB Source Codeforces Round #328 (Div. 2) Ari the monster is n ...
- 设置自己的APP能打开文件(在其他应用中打开显示自己的应用)
http://blog.csdn.net/leewolf130/article/details/29568961 http://www.jianshu.com/p/9711c3daf4bb https ...
- the command line tools
PhpStorm 10.0.2 http://stackoverflow.com/questions/22572861/error-cant-use-subversion-command-line-c ...
- IO、NIO、AIO理解
摘要: 关于BIO和NIO的理解 最近大概看了ZooKeeper和Mina的源码发现都是用Java NIO实现的,所以有必要搞清楚什么是NIO.下面是我结合网络资料自己总结的,为了节约时间图示随便画的 ...
- centos7 卸载和安装最新版本docker-ce,配置阿里云加速
一.yum卸载.安装 1.卸载老版本的 docker 及其相关依赖 sudo yum remove docker docker-common container-selinux docker-seli ...