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

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

using System.Data;
using System.IO;
using System.Text;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;/// <summary>
/// 使用NPOI操作Excel,无需Office COM组件
/// 部分代码取自http://msdn.microsoft.com/zh-tw/ee818993.asp
/// </summary>
public class ExcelRender
{/// <summary>/// 根据Excel列类型获取列的值/// </summary>/// <param name="cell">Excel列</param>/// <returns></returns>private static string GetCellValue(ICell cell){if (cell == null)return string.Empty;switch (cell.CellType){case CellType.BLANK:return string.Empty;case CellType.BOOLEAN:return cell.BooleanCellValue.ToString();case CellType.ERROR:return cell.ErrorCellValue.ToString();case CellType.NUMERIC:case CellType.Unknown:default: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 numbercase CellType.STRING:return cell.StringCellValue;case CellType.FORMULA:try{HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);e.EvaluateInCell(cell);return cell.ToString();}catch{return cell.NumericCellValue.ToString();} }}/// <summary>/// 自动设置Excel列宽/// </summary>/// <param name="sheet">Excel表</param>private static void AutoSizeColumns(ISheet sheet){if (sheet.PhysicalNumberOfRows > 0){IRow headerRow = sheet.GetRow(0);for (int i = 0, l = headerRow.LastCellNum; i < l; i++){sheet.AutoSizeColumn(i);}}}/// <summary>/// 保存Excel文档流到文件/// </summary>/// <param name="ms">Excel文档流</param>/// <param name="fileName">文件名</param>private static void SaveToFile(MemoryStream ms, string fileName){using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)){byte[] data = ms.ToArray();fs.Write(data, 0, data.Length);fs.Flush();data = null;}}/// <summary>/// 输出文件到浏览器/// </summary>/// <param name="ms">Excel文档流</param>/// <param name="context">HTTP上下文</param>/// <param name="fileName">文件名</param>private static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName){if (context.Request.Browser.Browser == "IE")fileName = HttpUtility.UrlEncode(fileName);context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);context.Response.BinaryWrite(ms.ToArray());}/// <summary>/// DataReader转换成Excel文档流/// </summary>/// <param name="reader"></param>/// <returns></returns>public static MemoryStream RenderToExcel(IDataReader reader){MemoryStream ms = new MemoryStream();using (reader){using (IWorkbook workbook = new HSSFWorkbook()){using (ISheet sheet = workbook.CreateSheet()){IRow headerRow = sheet.CreateRow(0);int cellCount = reader.FieldCount;// handling header.for (int i = 0; i < cellCount; i++){headerRow.CreateCell(i).SetCellValue(reader.GetName(i));}// handling value.int rowIndex = 1;while (reader.Read()){IRow dataRow = sheet.CreateRow(rowIndex);for (int i = 0; i < cellCount; i++){dataRow.CreateCell(i).SetCellValue(reader[i].ToString());}rowIndex++;}AutoSizeColumns(sheet);workbook.Write(ms);ms.Flush();ms.Position = 0;}}}return ms;}/// <summary>/// DataReader转换成Excel文档流,并保存到文件/// </summary>/// <param name="reader"></param>/// <param name="fileName">保存的路径</param>public static void RenderToExcel(IDataReader reader, string fileName){using (MemoryStream ms = RenderToExcel(reader)){SaveToFile(ms, fileName);}}/// <summary>/// DataReader转换成Excel文档流,并输出到客户端/// </summary>/// <param name="reader"></param>/// <param name="context">HTTP上下文</param>/// <param name="fileName">输出的文件名</param>public static void RenderToExcel(IDataReader reader, HttpContext context, string fileName){using (MemoryStream ms = RenderToExcel(reader)){RenderToBrowser(ms, context, fileName);}}/// <summary>/// DataTable转换成Excel文档流/// </summary>/// <param name="table"></param>/// <returns></returns>public static MemoryStream RenderToExcel(DataTable table){MemoryStream ms = new MemoryStream();using (table){using (IWorkbook workbook = new HSSFWorkbook()){using (ISheet sheet = workbook.CreateSheet()){IRow headerRow = sheet.CreateRow(0);// handling header.foreach (DataColumn column in table.Columns)headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value// handling value.int rowIndex = 1;foreach (DataRow row in table.Rows){IRow dataRow = sheet.CreateRow(rowIndex);foreach (DataColumn column in table.Columns){dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());}rowIndex++;}AutoSizeColumns(sheet);workbook.Write(ms);ms.Flush();ms.Position = 0;}}}return ms;}/// <summary>/// DataTable转换成Excel文档流,并保存到文件/// </summary>/// <param name="table"></param>/// <param name="fileName">保存的路径</param>public static void RenderToExcel(DataTable table, string fileName){using (MemoryStream ms = RenderToExcel(table)){SaveToFile(ms, fileName);}}/// <summary>/// DataTable转换成Excel文档流,并输出到客户端/// </summary>/// <param name="table"></param>/// <param name="response"></param>/// <param name="fileName">输出的文件名</param>public static void RenderToExcel(DataTable table, HttpContext context, string fileName){using (MemoryStream ms = RenderToExcel(table)){RenderToBrowser(ms, context, fileName);}}/// <summary>/// Excel文档流是否有数据/// </summary>/// <param name="excelFileStream">Excel文档流</param>/// <returns></returns>public static bool HasData(Stream excelFileStream){return HasData(excelFileStream, 0);}/// <summary>/// Excel文档流是否有数据/// </summary>/// <param name="excelFileStream">Excel文档流</param>/// <param name="sheetIndex">表索引号,如第一个表为0</param>/// <returns></returns>public static bool HasData(Stream excelFileStream, int sheetIndex){using (excelFileStream){using (IWorkbook workbook = new HSSFWorkbook(excelFileStream)){if (workbook.NumberOfSheets > 0){if (sheetIndex < workbook.NumberOfSheets){using (ISheet sheet = workbook.GetSheetAt(sheetIndex)){return sheet.PhysicalNumberOfRows > 0;}}}}}return false;}/// <summary>/// Excel文档流转换成DataTable/// 第一行必须为标题行/// </summary>/// <param name="excelFileStream">Excel文档流</param>/// <param name="sheetName">表名称</param>/// <returns></returns>public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName){return RenderFromExcel(excelFileStream, sheetName, 0);}/// <summary>/// Excel文档流转换成DataTable/// </summary>/// <param name="excelFileStream">Excel文档流</param>/// <param name="sheetName">表名称</param>/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>/// <returns></returns>public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex){DataTable table = null;using (excelFileStream){using (IWorkbook workbook = new HSSFWorkbook(excelFileStream)){using (ISheet sheet = workbook.GetSheet(sheetName)){table = RenderFromExcel(sheet, headerRowIndex);}}}return table;}/// <summary>/// Excel文档流转换成DataTable/// 默认转换Excel的第一个表/// 第一行必须为标题行/// </summary>/// <param name="excelFileStream">Excel文档流</param>/// <returns></returns>public static DataTable RenderFromExcel(Stream excelFileStream){return RenderFromExcel(excelFileStream, 0, 0);}/// <summary>/// Excel文档流转换成DataTable/// 第一行必须为标题行/// </summary>/// <param name="excelFileStream">Excel文档流</param>/// <param name="sheetIndex">表索引号,如第一个表为0</param>/// <returns></returns>public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex){return RenderFromExcel(excelFileStream, sheetIndex, 0);}/// <summary>/// Excel文档流转换成DataTable/// </summary>/// <param name="excelFileStream">Excel文档流</param>/// <param name="sheetIndex">表索引号,如第一个表为0</param>/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>/// <returns></returns>public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex){DataTable table = null;using (excelFileStream){using (IWorkbook workbook = new HSSFWorkbook(excelFileStream)){using (ISheet sheet = workbook.GetSheetAt(sheetIndex)){table = RenderFromExcel(sheet, headerRowIndex);}}}return table;}/// <summary>/// Excel表格转换成DataTable/// </summary>/// <param name="sheet">表格</param>/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>/// <returns></returns>private static DataTable RenderFromExcel(ISheet sheet, int headerRowIndex){DataTable table = new DataTable();IRow headerRow = sheet.GetRow(headerRowIndex);int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCellsint rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1//handling header.for (int i = headerRow.FirstCellNum; i < cellCount; i++){DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);table.Columns.Add(column);}for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++){IRow row = sheet.GetRow(i);DataRow dataRow = table.NewRow();if (row != null){for (int j = row.FirstCellNum; j < cellCount; j++){if (row.GetCell(j) != null)dataRow[j] = GetCellValue(row.GetCell(j));}}table.Rows.Add(dataRow);}return table;}/// <summary>/// Excel文档导入到数据库/// 默认取Excel的第一个表/// 第一行必须为标题行/// </summary>/// <param name="excelFileStream">Excel文档流</param>/// <param name="insertSql">插入语句</param>/// <param name="dbAction">更新到数据库的方法</param>/// <returns></returns>public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction){return RenderToDb(excelFileStream, insertSql, dbAction, 0, 0);}public delegate int DBAction(string sql, params IDataParameter[] parameters);/// <summary>/// Excel文档导入到数据库/// </summary>/// <param name="excelFileStream">Excel文档流</param>/// <param name="insertSql">插入语句</param>/// <param name="dbAction">更新到数据库的方法</param>/// <param name="sheetIndex">表索引号,如第一个表为0</param>/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>/// <returns></returns>public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction, int sheetIndex, int headerRowIndex){int rowAffected = 0;using (excelFileStream){using (IWorkbook workbook = new HSSFWorkbook(excelFileStream)){using (ISheet sheet = workbook.GetSheetAt(sheetIndex)){StringBuilder builder = new StringBuilder();IRow headerRow = sheet.GetRow(headerRowIndex);int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCellsint rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++){IRow row = sheet.GetRow(i);if (row != null){builder.Append(insertSql);builder.Append(" values (");for (int j = row.FirstCellNum; j < cellCount; j++){builder.AppendFormat("'{0}',", GetCellValue(row.GetCell(j)).Replace("'", "''"));}builder.Length = builder.Length - 1;builder.Append(");");}if ((i % 50 == 0 || i == rowCount) && builder.Length > 0){//每50条记录一次批量插入到数据库rowAffected += dbAction(builder.ToString());builder.Length = 0;}}}}}return rowAffected;}
}

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

ASP.NET操作Excel相关推荐

  1. asp.net操作Excel总结

    asp.net操作Excel是B/S架构开发报表中经常遇到的,现对常见操作总结如下: 以下来自孟子e章 DataGrid输出到Excel并进行格式化处理 用Xml2OleDb将XML文件插入到数据库 ...

  2. 告别ASP.NET操作EXCEL的烦恼

    Copy From 告别ASP.NET操作EXCEL的烦恼(总结篇) 公元19XX年前,关于EXCEL的操作就如滔滔江水,连绵不绝,真正操作EXCEL我也是从去年下半年开始的,有些比较复杂的年度报表之 ...

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

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

  4. 告别ASP.NET操作EXCEL的烦恼(总结篇)

    公元19XX年前,关于EXCEL的操作就如滔滔江水,连绵不绝,真正操作EXCEL我也是从去年下半年开始的,有些比较复杂的年度报表之类的,做起来也有点费力,不过还是都能画出来了,关于EXCEL的报表导出 ...

  5. 告别ASP.NET操作EXCEL的烦恼(总结篇)(转)

    公元19XX年前,关于EXCEL的操作就如滔滔江水,连绵不绝,真正操作EXCEL我也是从去年下半年开始的,有些比较复杂的年度报表之类的,做起来也有点费力,不过还是都能画出来了,关于EXCEL的报表导出 ...

  6. ASP.NET操作EXCEL时出现的错误 Retrieving the COM class factory for component with CLSID

    这个问题困扰了我很久,在网上找了很多资料都没用, 最后找到解决方案: 运行dcomcnfg打开组件服务 依次展开"组件服务"->"计算机"->&qu ...

  7. asp.net 操作excel的实现代码

    http://www.cnblogs.com/fywh/archive/2010/01/25/1655864.html 转载于:https://www.cnblogs.com/modernsky200 ...

  8. ASP.NET通过OLE DB操作Excel

    ASP.NET 操作Excel目前有比较多的方法,常用的有三种:COM组件,OLE DB,和NOPI插件. #1 COM组件 优点: (1)能读取各种版本的Excel,包括2003,2007,2010 ...

  9. oledb 操作 excel

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

最新文章

  1. php下dat函数e,PHP 常用函数记录 一
  2. 【ABAP】SUBMIT程序相互调用
  3. sql注入及mybatis防止sql注入
  4. python排序之sort和sorted
  5. 微信浏览器返回刷新,监听微信浏览器返回事件,网页防复制,移动端禁止图片长按和vivo手机点击img标签放大图片
  6. python的文件读写,序列化,复制/删除目录,压缩/解压缩/列出压缩文件目录,计算CRC32和MD5
  7. scalar2color
  8. Linux安装Wiznote为知笔记的方法
  9. edius隐藏快捷键_EDIUS快捷键大全
  10. gwipr70驱动天空_gwi驱动
  11. jmeter简单使用教程
  12. 通信原理最佳接收-匹配滤波器
  13. 完整的vue开发环境搭建教程
  14. html背景半透明 字不变,css实现背景半透明文字不透明的效果示例
  15. c语言程序窗口设计,C语言窗口程序设计简介.pdf
  16. python中死循环有用吗_Python里是否存在死循环
  17. 计算广告(五):搜索与竞价广告
  18. LeetCode之路:122. Best Time to Buy and Sell Stock II
  19. fckeditor是什么咚咚?
  20. 苹果cms模板_首涂第三套苹果CMSv10自适应视频站模板

热门文章

  1. 20个有用的 PHP + jQuery 组件和教程
  2. SpringCloud Ribbon
  3. 抽象类与抽象方法 c# 1613720553
  4. 草稿 修改数据 datagroupview
  5. 如何使用idea生成javaDoc文档
  6. selenium-入门与安装-0223
  7. python-面向对向编程-小结
  8. 修改linux ssh默认端口
  9. 理解*arg 、**kwargs
  10. Oracle-day03 上