使用NPOI操作Excel,无需Office COM组件

部分代码来自于:https://docs.microsoft.com/zh-tw/previous-versions/ee818993(v=msdn.10)?redirectedfrom=MSDN

  1. using System.Data;
  2. using System.IO;
  3. using System.Text;
  4. using System.Web;
  5. using NPOI.HSSF.UserModel;
  6. using NPOI.SS.UserModel;
  7.  
  8. /// <summary>
  9. /// 使用NPOI操作Excel,无需Office COM组件
  10. /// 部分代码取自http://msdn.microsoft.com/zh-tw/ee818993.asp
  11. /// </summary>
  12. public class ExcelRender
  13. {
  14. /// <summary>
  15. /// 根据Excel列类型获取列的值
  16. /// </summary>
  17. /// <param name="cell">Excel列</param>
  18. /// <returns></returns>
  19. private static string GetCellValue(ICell cell)
  20. {
  21. if (cell == null)
  22. return string.Empty;
  23. switch (cell.CellType)
  24. {
  25. case CellType.BLANK:
  26. return string.Empty;
  27. case CellType.BOOLEAN:
  28. return cell.BooleanCellValue.ToString();
  29. case CellType.ERROR:
  30. return cell.ErrorCellValue.ToString();
  31. case CellType.NUMERIC:
  32. case CellType.Unknown:
  33. default:
  34. return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
  35. case CellType.STRING:
  36. return cell.StringCellValue;
  37. case CellType.FORMULA:
  38. try
  39. {
  40. HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
  41. e.EvaluateInCell(cell);
  42. return cell.ToString();
  43. }
  44. catch
  45. {
  46. return cell.NumericCellValue.ToString();
  47. }
  48. }
  49. }
  50.  
  51. /// <summary>
  52. /// 自动设置Excel列宽
  53. /// </summary>
  54. /// <param name="sheet">Excel表</param>
  55. private static void AutoSizeColumns(ISheet sheet)
  56. {
  57. if (sheet.PhysicalNumberOfRows > )
  58. {
  59. IRow headerRow = sheet.GetRow();
  60.  
  61. for (int i = , l = headerRow.LastCellNum; i < l; i++)
  62. {
  63. sheet.AutoSizeColumn(i);
  64. }
  65. }
  66. }
  67.  
  68. /// <summary>
  69. /// 保存Excel文档流到文件
  70. /// </summary>
  71. /// <param name="ms">Excel文档流</param>
  72. /// <param name="fileName">文件名</param>
  73. private static void SaveToFile(MemoryStream ms, string fileName)
  74. {
  75. using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
  76. {
  77. byte[] data = ms.ToArray();
  78.  
  79. fs.Write(data, , data.Length);
  80. fs.Flush();
  81.  
  82. data = null;
  83. }
  84. }
  85.  
  86. /// <summary>
  87. /// 输出文件到浏览器
  88. /// </summary>
  89. /// <param name="ms">Excel文档流</param>
  90. /// <param name="context">HTTP上下文</param>
  91. /// <param name="fileName">文件名</param>
  92. private static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
  93. {
  94. if (context.Request.Browser.Browser == "IE")
  95. fileName = HttpUtility.UrlEncode(fileName);
  96. context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
  97. context.Response.BinaryWrite(ms.ToArray());
  98. }
  99.  
  100. /// <summary>
  101. /// DataReader转换成Excel文档流
  102. /// </summary>
  103. /// <param name="reader"></param>
  104. /// <returns></returns>
  105. public static MemoryStream RenderToExcel(IDataReader reader)
  106. {
  107. MemoryStream ms = new MemoryStream();
  108.  
  109. using (reader)
  110. {
  111. using (IWorkbook workbook = new HSSFWorkbook())
  112. {
  113. using (ISheet sheet = workbook.CreateSheet())
  114. {
  115. IRow headerRow = sheet.CreateRow();
  116. int cellCount = reader.FieldCount;
  117.  
  118. // handling header.
  119. for (int i = ; i < cellCount; i++)
  120. {
  121. headerRow.CreateCell(i).SetCellValue(reader.GetName(i));
  122. }
  123.  
  124. // handling value.
  125. int rowIndex = ;
  126. while (reader.Read())
  127. {
  128. IRow dataRow = sheet.CreateRow(rowIndex);
  129.  
  130. for (int i = ; i < cellCount; i++)
  131. {
  132. dataRow.CreateCell(i).SetCellValue(reader[i].ToString());
  133. }
  134.  
  135. rowIndex++;
  136. }
  137.  
  138. AutoSizeColumns(sheet);
  139.  
  140. workbook.Write(ms);
  141. ms.Flush();
  142. ms.Position = ;
  143. }
  144. }
  145. }
  146. return ms;
  147. }
  148.  
  149. /// <summary>
  150. /// DataReader转换成Excel文档流,并保存到文件
  151. /// </summary>
  152. /// <param name="reader"></param>
  153. /// <param name="fileName">保存的路径</param>
  154. public static void RenderToExcel(IDataReader reader, string fileName)
  155. {
  156. using (MemoryStream ms = RenderToExcel(reader))
  157. {
  158. SaveToFile(ms, fileName);
  159. }
  160. }
  161.  
  162. /// <summary>
  163. /// DataReader转换成Excel文档流,并输出到客户端
  164. /// </summary>
  165. /// <param name="reader"></param>
  166. /// <param name="context">HTTP上下文</param>
  167. /// <param name="fileName">输出的文件名</param>
  168. public static void RenderToExcel(IDataReader reader, HttpContext context, string fileName)
  169. {
  170. using (MemoryStream ms = RenderToExcel(reader))
  171. {
  172. RenderToBrowser(ms, context, fileName);
  173. }
  174. }
  175.  
  176. /// <summary>
  177. /// DataTable转换成Excel文档流
  178. /// </summary>
  179. /// <param name="table"></param>
  180. /// <returns></returns>
  181. public static MemoryStream RenderToExcel(DataTable table)
  182. {
  183. MemoryStream ms = new MemoryStream();
  184.  
  185. using (table)
  186. {
  187. using (IWorkbook workbook = new HSSFWorkbook())
  188. {
  189. using (ISheet sheet = workbook.CreateSheet())
  190. {
  191. IRow headerRow = sheet.CreateRow();
  192.  
  193. // handling header.
  194. foreach (DataColumn column in table.Columns)
  195. headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value
  196.  
  197. // handling value.
  198. int rowIndex = ;
  199.  
  200. foreach (DataRow row in table.Rows)
  201. {
  202. IRow dataRow = sheet.CreateRow(rowIndex);
  203.  
  204. foreach (DataColumn column in table.Columns)
  205. {
  206. dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
  207. }
  208.  
  209. rowIndex++;
  210. }
  211. AutoSizeColumns(sheet);
  212.  
  213. workbook.Write(ms);
  214. ms.Flush();
  215. ms.Position = ;
  216. }
  217. }
  218. }
  219. return ms;
  220. }
  221.  
  222. /// <summary>
  223. /// DataTable转换成Excel文档流,并保存到文件
  224. /// </summary>
  225. /// <param name="table"></param>
  226. /// <param name="fileName">保存的路径</param>
  227. public static void RenderToExcel(DataTable table, string fileName)
  228. {
  229. using (MemoryStream ms = RenderToExcel(table))
  230. {
  231. SaveToFile(ms, fileName);
  232. }
  233. }
  234.  
  235. /// <summary>
  236. /// DataTable转换成Excel文档流,并输出到客户端
  237. /// </summary>
  238. /// <param name="table"></param>
  239. /// <param name="response"></param>
  240. /// <param name="fileName">输出的文件名</param>
  241. public static void RenderToExcel(DataTable table, HttpContext context, string fileName)
  242. {
  243. using (MemoryStream ms = RenderToExcel(table))
  244. {
  245. RenderToBrowser(ms, context, fileName);
  246. }
  247. }
  248.  
  249. /// <summary>
  250. /// Excel文档流是否有数据
  251. /// </summary>
  252. /// <param name="excelFileStream">Excel文档流</param>
  253. /// <returns></returns>
  254. public static bool HasData(Stream excelFileStream)
  255. {
  256. return HasData(excelFileStream, );
  257. }
  258.  
  259. /// <summary>
  260. /// Excel文档流是否有数据
  261. /// </summary>
  262. /// <param name="excelFileStream">Excel文档流</param>
  263. /// <param name="sheetIndex">表索引号,如第一个表为0</param>
  264. /// <returns></returns>
  265. public static bool HasData(Stream excelFileStream, int sheetIndex)
  266. {
  267. using (excelFileStream)
  268. {
  269. using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
  270. {
  271. if (workbook.NumberOfSheets > )
  272. {
  273. if (sheetIndex < workbook.NumberOfSheets)
  274. {
  275. using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
  276. {
  277. return sheet.PhysicalNumberOfRows > ;
  278. }
  279. }
  280. }
  281. }
  282. }
  283. return false;
  284. }
  285.  
  286. /// <summary>
  287. /// Excel文档流转换成DataTable
  288. /// 第一行必须为标题行
  289. /// </summary>
  290. /// <param name="excelFileStream">Excel文档流</param>
  291. /// <param name="sheetName">表名称</param>
  292. /// <returns></returns>
  293. public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName)
  294. {
  295. return RenderFromExcel(excelFileStream, sheetName, );
  296. }
  297.  
  298. /// <summary>
  299. /// Excel文档流转换成DataTable
  300. /// </summary>
  301. /// <param name="excelFileStream">Excel文档流</param>
  302. /// <param name="sheetName">表名称</param>
  303. /// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
  304. /// <returns></returns>
  305. public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
  306. {
  307. DataTable table = null;
  308.  
  309. using (excelFileStream)
  310. {
  311. using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
  312. {
  313. using (ISheet sheet = workbook.GetSheet(sheetName))
  314. {
  315. table = RenderFromExcel(sheet, headerRowIndex);
  316. }
  317. }
  318. }
  319. return table;
  320. }
  321.  
  322. /// <summary>
  323. /// Excel文档流转换成DataTable
  324. /// 默认转换Excel的第一个表
  325. /// 第一行必须为标题行
  326. /// </summary>
  327. /// <param name="excelFileStream">Excel文档流</param>
  328. /// <returns></returns>
  329. public static DataTable RenderFromExcel(Stream excelFileStream)
  330. {
  331. return RenderFromExcel(excelFileStream, , );
  332. }
  333.  
  334. /// <summary>
  335. /// Excel文档流转换成DataTable
  336. /// 第一行必须为标题行
  337. /// </summary>
  338. /// <param name="excelFileStream">Excel文档流</param>
  339. /// <param name="sheetIndex">表索引号,如第一个表为0</param>
  340. /// <returns></returns>
  341. public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex)
  342. {
  343. return RenderFromExcel(excelFileStream, sheetIndex, );
  344. }
  345.  
  346. /// <summary>
  347. /// Excel文档流转换成DataTable
  348. /// </summary>
  349. /// <param name="excelFileStream">Excel文档流</param>
  350. /// <param name="sheetIndex">表索引号,如第一个表为0</param>
  351. /// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
  352. /// <returns></returns>
  353. public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)
  354. {
  355. DataTable table = null;
  356.  
  357. using (excelFileStream)
  358. {
  359. using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
  360. {
  361. using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
  362. {
  363. table = RenderFromExcel(sheet, headerRowIndex);
  364. }
  365. }
  366. }
  367. return table;
  368. }
  369.  
  370. /// <summary>
  371. /// Excel表格转换成DataTable
  372. /// </summary>
  373. /// <param name="sheet">表格</param>
  374. /// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
  375. /// <returns></returns>
  376. private static DataTable RenderFromExcel(ISheet sheet, int headerRowIndex)
  377. {
  378. DataTable table = new DataTable();
  379.  
  380. IRow headerRow = sheet.GetRow(headerRowIndex);
  381. int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
  382. int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
  383.  
  384. //handling header.
  385. for (int i = headerRow.FirstCellNum; i < cellCount; i++)
  386. {
  387. DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
  388. table.Columns.Add(column);
  389. }
  390.  
  391. for (int i = (sheet.FirstRowNum + ); i <= rowCount; i++)
  392. {
  393. IRow row = sheet.GetRow(i);
  394. DataRow dataRow = table.NewRow();
  395.  
  396. if (row != null)
  397. {
  398. for (int j = row.FirstCellNum; j < cellCount; j++)
  399. {
  400. if (row.GetCell(j) != null)
  401. dataRow[j] = GetCellValue(row.GetCell(j));
  402. }
  403. }
  404.  
  405. table.Rows.Add(dataRow);
  406. }
  407.  
  408. return table;
  409. }
  410.  
  411. /// <summary>
  412. /// Excel文档导入到数据库
  413. /// 默认取Excel的第一个表
  414. /// 第一行必须为标题行
  415. /// </summary>
  416. /// <param name="excelFileStream">Excel文档流</param>
  417. /// <param name="insertSql">插入语句</param>
  418. /// <param name="dbAction">更新到数据库的方法</param>
  419. /// <returns></returns>
  420. public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction)
  421. {
  422. return RenderToDb(excelFileStream, insertSql, dbAction, , );
  423. }
  424.  
  425. public delegate int DBAction(string sql, params IDataParameter[] parameters);
  426.  
  427. /// <summary>
  428. /// Excel文档导入到数据库
  429. /// </summary>
  430. /// <param name="excelFileStream">Excel文档流</param>
  431. /// <param name="insertSql">插入语句</param>
  432. /// <param name="dbAction">更新到数据库的方法</param>
  433. /// <param name="sheetIndex">表索引号,如第一个表为0</param>
  434. /// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
  435. /// <returns></returns>
  436. public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction, int sheetIndex, int headerRowIndex)
  437. {
  438. int rowAffected = ;
  439. using (excelFileStream)
  440. {
  441. using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
  442. {
  443. using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
  444. {
  445. StringBuilder builder = new StringBuilder();
  446.  
  447. IRow headerRow = sheet.GetRow(headerRowIndex);
  448. int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
  449. int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
  450.  
  451. for (int i = (sheet.FirstRowNum + ); i <= rowCount; i++)
  452. {
  453. IRow row = sheet.GetRow(i);
  454. if (row != null)
  455. {
  456. builder.Append(insertSql);
  457. builder.Append(" values (");
  458. for (int j = row.FirstCellNum; j < cellCount; j++)
  459. {
  460. builder.AppendFormat("'{0}',", GetCellValue(row.GetCell(j)).Replace("'", "''"));
  461. }
  462. builder.Length = builder.Length - ;
  463. builder.Append(");");
  464. }
  465.  
  466. if ((i % == || i == rowCount) && builder.Length > )
  467. {
  468. //每50条记录一次批量插入到数据库
  469. rowAffected += dbAction(builder.ToString());
  470. builder.Length = ;
  471. }
  472. }
  473. }
  474. }
  475. }
  476. return rowAffected;
  477. }
  478. }

弄一个DBheple 就可以完成该操作Excel

ASP.NET操作Excel的更多相关文章

  1. asp.net 操作Excel大全

    asp.net 操作Excel大全 转:http://www.cnblogs.com/zhangchenliang/archive/2011/07/21/2112430.html 我们在做excel资 ...

  2. Asp.net操作Excel(终极方法NPOI)(转)

    原文:Asp.net操作Excel(终极方法NPOI) 先去官网:http://npoi.codeplex.com/下载需要引入dll(可以选择.net2.0或者.net4.0的dll),然后在网站中 ...

  3. ASP.NET操作Excel(终极方法NPOI)

    ASP.NET操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,能够帮助开发者在没有安装微软Office的情况下读写Office 97-200 ...

  4. ASP.NET 操作Excel中的DCOM配置方式

    具体配置方式如下: 1. 组件服务管理窗口 在运行栏中输入命令:dcomcnfg,打开组件服务管理窗口,在组件服务->计算机->我的电脑->DCom配置->找到Microsof ...

  5. asp.net 操作excel的一系列问题(未完待续)

    最近在处理exel的一些东西,遇到了很多问题,现在就在此将问题和网上找到的解决办法 1.外部表不是预期格式错误 错误经过:在读取Excel时,出现外部表不是预期的格式 错误原因1: 由于Excel 9 ...

  6. Asp.Net使用org.in2bits.MyXls.dll操作excel的应用

    首先下载org.in2bits.MyXls.dll(自己的在~\About ASP.Net\Asp.Net操作excel) 添加命名空间: using org.in2bits.MyXls;using ...

  7. Asp.net操作Excel----NPOI!!!!1

    前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使 用NPOI能够帮助开发者在没有安装微软Office的情况下读写Off ...

  8. oledb 操作 excel

    oledb excel http://wenku.baidu.com/search?word=oledb%20excel&ie=utf-8&lm=0&od=0 [Asp.net ...

  9. ASP.NET Core使用EPPlus操作Excel

    1.前言 本篇文章通过ASP.NET Core的EPPlus包去操作Excel(导入导出),其使用原理与NPOI类似,导出Excel的时候不需要电脑上安装office,非常好用 2.使用 新建一个AS ...

随机推荐

  1. 教你用Java web实现多条件过滤功能

    生活中,当你闲暇之余浏览资讯的时候,当你搜索资料但繁杂信息夹杂时候,你就会想,如何更为准确的定位需求信息.今天就为你带来: 分页查询 需求分析:在列表页面中,显示指定条数的数据,通过翻页按钮完成首页/ ...

  2. ORA-00845 startup启动不起来关于磁盘空间扩充

    问题描述:今天在虚拟机下进行startup的操作,但是没有起来,系统报错:ORA-00845: MEMORY_TARGET not supported on this system 1.startup ...

  3. vue 结合 Echarts 实现半开环形图

    Echarts 实现半开环形图 1.先看看实现的图 2.HTML部分 创建id 是 chart 的div标签. <div class="content-item"> & ...

  4. Djangoday3template

    template第一个demo从后台传递数据到前端从后台传递list前端for循环显示内容后台传输dict到前端 template第一个demo template存在app/templates目录下 ...

  5. js表达式和语句趣味题讲解与技术分享

    技术分享 问题1 { a: 1 } + 1 // ? ({ a: 1 }) + 1 // ? 1 + { a: 1 } // ? 答案 { a: 1 } + 1 // 1 ({ a: 1 }) + 1 ...

  6. 最新Navicat Premium12 破解方法,亲测可用

    1.下载Navicat Premium 官网https://www.navicat.com.cn/下载最新版本下载安装(文末,网盘地址有64位安装包和注册机下载) 2.激活Navicat Premiu ...

  7. Python--glob模块

    0.glob模块和通配符 glob模块最主要的方法有2个: 1.glob() 2.iglob() 以上2分方法一般和通配符一起使用,常用的通配符有3个: * :匹配零个或多个字符 ? :匹配任何单个的 ...

  8. [TimLinux] MySQL InnoDB的外键约束不支持set default引用选项

    1. 外键 MySQL的MyISAM是不支持外键的,InnoDB支持外键,外键是MySQL中的三大约束中的一类:主键约束(PRIMARY KEY),唯一性约束(UNIQUE),外键约束(FOREIGN ...

  9. CF372C Watching Fireworks is Fun(单调队列优化DP)

    A festival will be held in a town's main street. There are n sections in the main street. The sectio ...

  10. CSU-2018

    The gaming company Sandstorm is developing an online two player game. You have been asked to impleme ...