一、下载引用

下载需要引用的dll,即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll(office2007版需要此dll)。

二、excel转datatable类

  1. using System;
  2. using System.Data;
  3. using System.IO;
  4. using NPOI.SS.UserModel;
  5. using NPOI.XSSF.UserModel;
  6. using NPOI.HSSF.UserModel;
  7. namespace NPOIOprateExcel
  8. {
  9. public class ExcelUtility
  10. {
  11. /// <summary>
  12. /// 将excel导入到datatable
  13. /// </summary>
  14. /// <param name="filePath">excel路径</param>
  15. /// <param name="isColumnName">第一行是否是列名</param>
  16. /// <returns>返回datatable</returns>
  17. public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
  18. {
  19. DataTable dataTable = null;
  20. FileStream fs = null;
  21. DataColumn column = null;
  22. DataRow dataRow = null;
  23. IWorkbook workbook = null;
  24. ISheet sheet = null;
  25. IRow row = null;
  26. ICell cell = null;
  27. int startRow = 0;
  28. try
  29. {
  30. using (fs = File.OpenRead(filePath))
  31. {
  32. // 2007版本
  33. if (filePath.IndexOf(".xlsx") > 0)
  34. workbook = new XSSFWorkbook(fs);
  35. // 2003版本
  36. else if (filePath.IndexOf(".xls") > 0)
  37. workbook = new HSSFWorkbook(fs);
  38. if (workbook != null)
  39. {
  40. sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
  41. dataTable = new DataTable();
  42. if (sheet != null)
  43. {
  44. int rowCount = sheet.LastRowNum;//总行数
  45. if (rowCount > 0)
  46. {
  47. IRow firstRow = sheet.GetRow(0);//第一行
  48. int cellCount = firstRow.LastCellNum;//列数
  49. //构建datatable的列
  50. if (isColumnName)
  51. {
  52. startRow = 1;//如果第一行是列名,则从第二行开始读取
  53. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  54. {
  55. cell = firstRow.GetCell(i);
  56. if (cell != null)
  57. {
  58. if (cell.StringCellValue != null)
  59. {
  60. column = new DataColumn(cell.StringCellValue);
  61. dataTable.Columns.Add(column);
  62. }
  63. }
  64. }
  65. }
  66. else
  67. {
  68. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  69. {
  70. column = new DataColumn("column" + (i + 1));
  71. dataTable.Columns.Add(column);
  72. }
  73. }
  74. //填充行
  75. for (int i = startRow; i <= rowCount; ++i)
  76. {
  77. row = sheet.GetRow(i);
  78. if (row == null) continue;
  79. dataRow = dataTable.NewRow();
  80. for (int j = row.FirstCellNum; j < cellCount; ++j)
  81. {
  82. cell = row.GetCell(j);
  83. if (cell == null)
  84. {
  85. dataRow[j] = "";
  86. }
  87. else
  88. {
  89. //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
  90. switch (cell.CellType)
  91. {
  92. case CellType.Blank:
  93. dataRow[j] = "";
  94. break;
  95. case CellType.Numeric:
  96. short format = cell.CellStyle.DataFormat;
  97. //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
  98. if (format == 14 || format == 31 || format == 57 || format == 58)
  99. dataRow[j] = cell.DateCellValue;
  100. else
  101. dataRow[j] = cell.NumericCellValue;
  102. break;
  103. case CellType.String:
  104. dataRow[j] = cell.StringCellValue;
  105. break;
  106. }
  107. }
  108. }
  109. dataTable.Rows.Add(dataRow);
  110. }
  111. }
  112. }
  113. }
  114. }
  115. return dataTable;
  116. }
  117. catch (Exception)
  118. {
  119. if (fs != null)
  120. {
  121. fs.Close();
  122. }
  123. return null;
  124. }
  125. }
  126. }
  127. }

三、结果

四、写入excel类

  1. public static bool DataTableToExcel(DataTable dt)
  2. {
  3. bool result = false;
  4. IWorkbook workbook = null;
  5. FileStream fs = null;
  6. IRow row = null;
  7. ISheet sheet = null;
  8. ICell cell = null;
  9. try
  10. {
  11. if (dt != null && dt.Rows.Count > 0)
  12. {
  13. workbook = new HSSFWorkbook();
  14. sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
  15. int rowCount = dt.Rows.Count;//行数
  16. int columnCount = dt.Columns.Count;//列数
  17. //设置列头
  18. row = sheet.CreateRow(0);//excel第一行设为列头
  19. for (int c = 0; c < columnCount; c++)
  20. {
  21. cell = row.CreateCell(c);
  22. cell.SetCellValue(dt.Columns[c].ColumnName);
  23. }
  24. //设置每行每列的单元格,
  25. for (int i = 0; i <rowCount; i++)
  26. {
  27. row = sheet.CreateRow(i+1);
  28. for (int j = 0; j < columnCount; j++)
  29. {
  30. cell = row.CreateCell(j);//excel第二行开始写入数据
  31. cell.SetCellValue(dt.Rows[i][j].ToString());
  32. }
  33. }
  34. using (fs = File.OpenWrite(@"D:/myxls.xls"))
  35. {
  36. workbook.Write(fs);//向打开的这个xls文件中写入数据
  37. result = true;
  38. }
  39. }
  40. return result;
  41. }
  42. catch (Exception ex)
  43. {
  44. if (fs != null)
  45. {
  46. fs.Close();
  47. }
  48. return false;
  49. }
  50. }

结果如下:

源码地址:http://download.csdn.net/detail/coderk2014/9328779

C#中NPOI操作excel之读取和写入excel数据的更多相关文章

  1. C#中创建、打开、读取、写入、保存Excel的一般性代码

    ---转载:http://hi.baidu.com/zhaocbo/item/e840bcf941932d15fe358228 1. Excel对象微软的Excel对象模型包括了128个不同的对象,从 ...

  2. Java使用POI读取和写入Excel指南

    Java使用POI读取和写入Excel指南 做项目时经常有通过程序读取Excel数据,或是创建新的Excel并写入数据的需求: 网上很多经验教程里使用的POI版本都比较老了,一些API在新版里已经废弃 ...

  3. Java使用POI读取和写入Excel指南(转)

    做项目时经常有通过程序读取Excel数据,或是创建新的Excel并写入数据的需求: 网上很多经验教程里使用的POI版本都比较老了,一些API在新版里已经废弃,这里基于最新的Apache POI 4.0 ...

  4. C#中npoi操作Excel[版本2.0.1读写2003、2007格式]

    下载npoi2.0.1dll文件:http://download.csdn.net/detail/pukuimin1226/5851747 public static void test1()     ...

  5. 一个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 ...

  6. 读取、写入excel数据

    在实际项目中,不可避免的会操作excel表格.一直以来都是读取excel表格,可今天为了写入excel表格,可是煞费苦心,终于完成,记录下来以便后续使用. 1.读取excel表格的数据 读取excel ...

  7. Java 使用Apache POI读取和写入Excel表格

    1,引入所用的包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxm ...

  8. Python3 读取和写入excel

    https://blog.csdn.net/weixin_43094965/article/details/82226263一.Excel 1.Excel文件三个对象 workbook: 工作簿,一个 ...

  9. MATLAB读取和写入Excel文件

    1. 读取Excel文件 (a) 命令方式xlsread:  读取命令:[data,text]  = xlsread(FileName, SheetName, Range); data保存的是数据单元 ...

随机推荐

  1. linux下php的一些问题

    一.Loaded Configuration File  none Configuration File (php.ini) Path /data/service/php/etc 在etc目录下有ph ...

  2. iOS - 视频播放处理全屏/横屏时候遇见的坑

    视频播放想要全屏,使用shouldAutorotate方法禁止主界面,tabbar控制器横屏,导致push进入播放页面不能横屏的问题... - (BOOL)shouldAutorotate { ret ...

  3. elasticsearch的索引自动清理及自定义清理

    近发现elasticsearch近期索引文件大的吓人,清理了下之前的索引文件,发现服务器性能大大的减轻了一半,想一直保留近一个月的索引文件,但是又不想每个月手动清楚,在此写了一个小脚本 查询索引: c ...

  4. Pointer Lock

    Pointer Lock API 指针锁定(以前叫做 鼠标锁定) 提供了一种输入方法,这种方法是基于鼠标随着时间推移的运动的(也就是说,deltas),而不仅是鼠标光标的绝对位置.通过它可以访问原始的 ...

  5. Nginx通过header转发

    假设添加自定义头 "my-header",当"my-header"等于test时,转发到192.168.1.113 请求如下 wget --header=&qu ...

  6. Python通过正则表达式去除(过滤)HTML标签,提取文字

    # -*- coding: utf-8-*- import re ##过滤HTML中的标签 #将HTML中标签等信息去掉 #@param htmlstr HTML字符串. def filter_tag ...

  7. js备忘录_2

    JS函数的参数在function内可以用arguments对象来获取. 转化为数组:var arr=Array.prototype.slice.call(arguments,0); Array有两个: ...

  8. ceil 和floor

    ceil 天花板 floor 地板 ceil向上取整 foor向下取整

  9. ELKStack

    ELKStack简介        对于日志来说,最常见的需求就是收集.存储.查询.展示,开源社区正好有相对应的开源项目:logstash(收集).elasticsearch(存储+搜索).kiban ...

  10. POJ 1986 - Distance Queries - [LCA模板题][Tarjan-LCA算法]

    题目链接:http://poj.org/problem?id=1986 Description Farmer John's cows refused to run in his marathon si ...