ASP.NET操作Excel
使用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 number
- case 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 > )
- {
- IRow headerRow = sheet.GetRow();
- for (int i = , 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, , 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();
- int cellCount = reader.FieldCount;
- // handling header.
- for (int i = ; i < cellCount; i++)
- {
- headerRow.CreateCell(i).SetCellValue(reader.GetName(i));
- }
- // handling value.
- int rowIndex = ;
- while (reader.Read())
- {
- IRow dataRow = sheet.CreateRow(rowIndex);
- for (int i = ; i < cellCount; i++)
- {
- dataRow.CreateCell(i).SetCellValue(reader[i].ToString());
- }
- rowIndex++;
- }
- AutoSizeColumns(sheet);
- workbook.Write(ms);
- ms.Flush();
- ms.Position = ;
- }
- }
- }
- 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();
- // 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 = ;
- 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 = ;
- }
- }
- }
- 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, );
- }
- /// <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 > )
- {
- if (sheetIndex < workbook.NumberOfSheets)
- {
- using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
- {
- return sheet.PhysicalNumberOfRows > ;
- }
- }
- }
- }
- }
- 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, );
- }
- /// <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, , );
- }
- /// <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, );
- }
- /// <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 = PhysicalNumberOfCells
- int 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 + ); 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, , );
- }
- 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 = ;
- 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 = PhysicalNumberOfCells
- int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
- for (int i = (sheet.FirstRowNum + ); 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 - ;
- builder.Append(");");
- }
- if ((i % == || i == rowCount) && builder.Length > )
- {
- //每50条记录一次批量插入到数据库
- rowAffected += dbAction(builder.ToString());
- builder.Length = ;
- }
- }
- }
- }
- }
- return rowAffected;
- }
- }
弄一个DBheple 就可以完成该操作Excel
ASP.NET操作Excel的更多相关文章
- asp.net 操作Excel大全
asp.net 操作Excel大全 转:http://www.cnblogs.com/zhangchenliang/archive/2011/07/21/2112430.html 我们在做excel资 ...
- Asp.net操作Excel(终极方法NPOI)(转)
原文:Asp.net操作Excel(终极方法NPOI) 先去官网:http://npoi.codeplex.com/下载需要引入dll(可以选择.net2.0或者.net4.0的dll),然后在网站中 ...
- ASP.NET操作Excel(终极方法NPOI)
ASP.NET操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,能够帮助开发者在没有安装微软Office的情况下读写Office 97-200 ...
- ASP.NET 操作Excel中的DCOM配置方式
具体配置方式如下: 1. 组件服务管理窗口 在运行栏中输入命令:dcomcnfg,打开组件服务管理窗口,在组件服务->计算机->我的电脑->DCom配置->找到Microsof ...
- asp.net 操作excel的一系列问题(未完待续)
最近在处理exel的一些东西,遇到了很多问题,现在就在此将问题和网上找到的解决办法 1.外部表不是预期格式错误 错误经过:在读取Excel时,出现外部表不是预期的格式 错误原因1: 由于Excel 9 ...
- Asp.Net使用org.in2bits.MyXls.dll操作excel的应用
首先下载org.in2bits.MyXls.dll(自己的在~\About ASP.Net\Asp.Net操作excel) 添加命名空间: using org.in2bits.MyXls;using ...
- Asp.net操作Excel----NPOI!!!!1
前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使 用NPOI能够帮助开发者在没有安装微软Office的情况下读写Off ...
- oledb 操作 excel
oledb excel http://wenku.baidu.com/search?word=oledb%20excel&ie=utf-8&lm=0&od=0 [Asp.net ...
- ASP.NET Core使用EPPlus操作Excel
1.前言 本篇文章通过ASP.NET Core的EPPlus包去操作Excel(导入导出),其使用原理与NPOI类似,导出Excel的时候不需要电脑上安装office,非常好用 2.使用 新建一个AS ...
随机推荐
- 教你用Java web实现多条件过滤功能
生活中,当你闲暇之余浏览资讯的时候,当你搜索资料但繁杂信息夹杂时候,你就会想,如何更为准确的定位需求信息.今天就为你带来: 分页查询 需求分析:在列表页面中,显示指定条数的数据,通过翻页按钮完成首页/ ...
- ORA-00845 startup启动不起来关于磁盘空间扩充
问题描述:今天在虚拟机下进行startup的操作,但是没有起来,系统报错:ORA-00845: MEMORY_TARGET not supported on this system 1.startup ...
- vue 结合 Echarts 实现半开环形图
Echarts 实现半开环形图 1.先看看实现的图 2.HTML部分 创建id 是 chart 的div标签. <div class="content-item"> & ...
- Djangoday3template
template第一个demo从后台传递数据到前端从后台传递list前端for循环显示内容后台传输dict到前端 template第一个demo template存在app/templates目录下 ...
- js表达式和语句趣味题讲解与技术分享
技术分享 问题1 { a: 1 } + 1 // ? ({ a: 1 }) + 1 // ? 1 + { a: 1 } // ? 答案 { a: 1 } + 1 // 1 ({ a: 1 }) + 1 ...
- 最新Navicat Premium12 破解方法,亲测可用
1.下载Navicat Premium 官网https://www.navicat.com.cn/下载最新版本下载安装(文末,网盘地址有64位安装包和注册机下载) 2.激活Navicat Premiu ...
- Python--glob模块
0.glob模块和通配符 glob模块最主要的方法有2个: 1.glob() 2.iglob() 以上2分方法一般和通配符一起使用,常用的通配符有3个: * :匹配零个或多个字符 ? :匹配任何单个的 ...
- [TimLinux] MySQL InnoDB的外键约束不支持set default引用选项
1. 外键 MySQL的MyISAM是不支持外键的,InnoDB支持外键,外键是MySQL中的三大约束中的一类:主键约束(PRIMARY KEY),唯一性约束(UNIQUE),外键约束(FOREIGN ...
- 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 ...
- CSU-2018
The gaming company Sandstorm is developing an online two player game. You have been asked to impleme ...