1.使用OLEDB导出Excel  ,这种方式有点慢,慎用
 /// <summary>
/// 使用OLEDB导出Excel
/// </summary>
/// <param name="dt"></param>
/// <param name="filepath"></param>
/// <param name="tablename"></param> public static void Export(System.Data.DataTable dt, string filepath, string tablename)
{ //excel 2003格式 // string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;"; //Excel 2007格式 string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0 Xml;"; try
{ using (OleDbConnection con = new OleDbConnection(connString))
{
con.Open();
StringBuilder strSQL = new StringBuilder();
strSQL.Append("CREATE TABLE ").Append("[" + tablename + "]"); strSQL.Append("(");
for (int i = ; i < dt.Columns.Count; i++)
{
strSQL.Append("[" + dt.Columns[i].ColumnName + "] text,"); }
strSQL = strSQL.Remove(strSQL.Length - , );
strSQL.Append(")"); OleDbCommand cmd = new OleDbCommand(strSQL.ToString(), con);
cmd.ExecuteNonQuery();
for (int i = ; i < dt.Rows.Count; i++)
{
strSQL.Clear(); StringBuilder strfield = new StringBuilder(); StringBuilder strvalue = new StringBuilder(); for (int j = ; j < dt.Columns.Count; j++)
{ strfield.Append("[" + dt.Columns[j].ColumnName + "]"); strvalue.Append("'" + dt.Rows[i][j].ToString() + "'"); if (j != dt.Columns.Count - )
{ strfield.Append(","); strvalue.Append(","); } else
{ } } cmd.CommandText = strSQL.Append(" insert into [" + tablename + "]( ") .Append(strfield.ToString()) .Append(") values (").Append(strvalue).Append(")").ToString(); cmd.ExecuteNonQuery(); } con.Close(); } Console.WriteLine("OK"); } catch (Exception ex)
{ Console.WriteLine(ex.Message); } }

2.NPOI 导出excel

2007 版

  public FileResult Export(SC_ServiceCardUsedRecordSearchParam param)
{ int cou = ; //创建Excel文件的对象
//NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();// NPOI.XSSF.UserModel.XSSFWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook();
//NPOI.XSSF.UserModel.XSSFWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
//添加一个sheet
//NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1"); // NPOI.SS.UserModel.ISheet sheet1= book.CreateSheet("Sheet1"); // List<SC_ServiceCardUsedRecord> cards = new List<SC_ServiceCardUsedRecord>(); //获取list数据
cards = _AppContext.ServiceCardUsedRecordApp.SelectRecordList(param).ToList<SC_ServiceCardUsedRecord>(); //给sheet1添加第一行的头部标题
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow();
row1.CreateCell().SetCellValue("编号");
row1.CreateCell().SetCellValue("卡券号码");
row1.CreateCell().SetCellValue("手机号");
row1.CreateCell().SetCellValue("姓名");
row1.CreateCell().SetCellValue("车架号");
row1.CreateCell().SetCellValue("经销商");
row1.CreateCell().SetCellValue("行驶里程");
row1.CreateCell().SetCellValue("创建时间");
row1.CreateCell().SetCellValue("卡劵类型");
row1.CreateCell().SetCellValue("车型");
row1.CreateCell().SetCellValue("来源");
row1.CreateCell().SetCellValue("经销商名称");
row1.CreateCell().SetCellValue("发卡时间");
row1.CreateCell().SetCellValue("购车时间");
row1.CreateCell().SetCellValue("会员等级"); //将数据逐步写入sheet1各个行
for (int i = ; i < cards.Count(); i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + ); rowtemp.CreateCell().SetCellValue(cards[i].Id.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].CardNo.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].PhoneNumber.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].CustName == null ? "" : cards[i].CustName.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].VIN == null ? "" : cards[i].VIN.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].DealerId == null ? "" : cards[i].DealerId.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].Mileage == null ? "" : cards[i].Mileage.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].CreateTime.ToLongDateString());
rowtemp.CreateCell().SetCellValue(cards[i].CardTypeName == null ? "" : cards[i].CardTypeName.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].CarCategory == null ? "" : cards[i].CarCategory.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].ActivityTag == null ? "" : cards[i].ActivityTag.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].DealerName == null ? "" : cards[i].DealerName.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].kqCreateTime == null ? "" : cards[i].kqCreateTime.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].BuyTime == null ? "" : cards[i].BuyTime.ToString());
rowtemp.CreateCell().SetCellValue(cards[i].MLevel == null ? "" : cards[i].MLevel.ToString()); } // 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
// MemoryStream stream = new MemoryStream();
book.Write(ms);
var buf = ms.ToArray();
//ms.Seek(0, SeekOrigin.Begin); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
//return File(ms, "application/vnd.ms-excel", "Card.xlsx");
return File(buf, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Card.xlsx");
}

2003 版

        public ActionResult Export(DateTime? startTime, DateTime? endTime, string tableName)
{
IWorkbook book = new HSSFWorkbook(); //获取list数据
DataTable dt = _AppContext.ReportApp.GetReport(startTime ?? DateTime.Now.AddDays(-), endTime ?? DateTime.Now, tableName); if (dt.Rows.Count < EXCEL03_MaxRow)
DataWrite2Sheet(dt, , dt.Rows.Count - , book, "Sheet1");
else
{
int page = dt.Rows.Count / EXCEL03_MaxRow;
for (int i = ; i < page; i++)
{
int start = i * EXCEL03_MaxRow;
int end = (i * EXCEL03_MaxRow) + EXCEL03_MaxRow - ;
DataWrite2Sheet(dt, start, end, book, "Sheet" + i.ToString());
}
int lastPageItemCount = dt.Rows.Count % EXCEL03_MaxRow;
DataWrite2Sheet(dt, dt.Rows.Count - lastPageItemCount, dt.Rows.Count - , book, "Sheet" + page.ToString());
} // 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
ms.Seek(, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", tableName + ".xls");
}

注意:操作Excel2003与操作Excel2007使用的是不同的命名空间下的内容

使用NPOI.HSSF.UserModel空间下的HSSFWorkbook操作Excel2003

使用NPOI.XSSF.UserModel空间下的XSSFWorkbook操作Excel2007

asp.net 导出excel--NPOI的更多相关文章

  1. Asp.net导出Excel续章(自定义合并单元格,非Office组件)

    结合上次写的导出Excel方法,这次上头要求我将列头进行一下合并 以前的效果: 改进后的效果: 在上篇文章中写到了Excel的导出方法,这次为了避免在生产环境中使用Office组件,服务器各种权限配置 ...

  2. asp.net导出excel示例代码

    asp.net导出excel的简单方法. excel的操作,最常用的就是导出和导入. 本例使用NPOI实现. 代码:/// <summary> );             ;       ...

  3. [转] Asp.Net 导出 Excel 数据的9种方案

    湛刚 de BLOG 原文地址 Asp.Net 导出 Excel 数据的9种方案 简介 Excel 的强大之处在于它不仅仅只能打开Excel格式的文档,它还能打开CSV格式.Tab格式.website ...

  4. ASP.NET导出EXCEL类

    最新ASP.NET导出EXCEL类 说明:可以导出ASP.NET页面和DATAGRID(WebControl)数据,可以导出表单头 using System;using System.Data;usi ...

  5. asp.net导出excel并弹出保存提示框

    asp.net导出excel并弹出保存提示框 2013-07-12 | 阅:1  转:78   |  分享  腾讯空间 人人网 开心网 新浪微博 腾讯微博 搜狐空间 推荐给朋友 举报          ...

  6. ASP.NET导出Excel(利用NPOI和EPPlus库,无需安装Office)

    网上提供了很多Asp.net中操作Excel的方法,其中大部分是调用微软的Office组件,下面提供三个无须安装Office即可从Asp.net输出Excel的方法. 1 简单方法 //下面代码输出的 ...

  7. ASP.NET MVC导出excel npoi

    使用npoi组件 前端代码: @Html.ActionLink("导出Excel", "ExportWarehouseInOutDetailTable", ne ...

  8. asp.net 导出Excel

    分享一个asp.net 导出假Excel代码.优点,不用借助于任何插件比如(NPOI),复制代码,修改grid.DataSource直接导出. 先看导出后的效果图 System.Web.UI.WebC ...

  9. ASP.NETCore -----导出Excel文件并下载

    本事例分为nopi(安装DotNetCore.NPOI)下载和EPPlus(EPPlus.Core.dll)下载,其中npoi下载演示的是根据执行的模板进行数据下载 npoi帮助类NpoiExcelU ...

  10. Asp.net导出Excel乱码的解决方法

    通过跟踪Asp.net服务器代码,没有乱码,然而导出Excel到浏览器后,打开时出现乱码. 解决方法是添加编码格式的前缀字节码:Response.BinaryWrite(System.Text.Enc ...

随机推荐

  1. Git分支操作——查看、新建、删除、提交、合并

    查看分支 1 查看本地分支 $ git branch   2 查看远程分支 $ git branch -r     创建分支 1 创建本地分支 $ git branch branchName 2 切换 ...

  2. 解决space-between最后一排问题

    display:flex + justify-content: space-between 能够实现2端对齐的布局,这种布局在网页中很常见.不过这种布局方式有一个问题.举个例子,我们假设现在一排放4个 ...

  3. github控件地址

    地址: https://github.com/wasabeef/awesome-android-ui http://www.jcodecraeer.com/plus/list.php?tid=31 h ...

  4. springboot-thymeleaf

    Thymeleaf 是一个跟 Velocity.FreeMarker 类似的模板引擎,它可以完全替代 JSP .相较与其他的模板引擎,它有如下三个极吸引人的特点: Thymeleaf 在有网络和无网络 ...

  5. 24访问者模式Visitor

    一.什么是访问者模式 Visitor模式也叫访问者模式,是行为模式之一 ,它分离对象的数据和行为,使用Visitor模式, 可以不修改已有类的情况下,增加新的操作. 二.访问者模式的应用示例 比如有一 ...

  6. 使用DDL触发器同步多个数据库结构

    使用DDL触发器同步多个数据库结构 背景:当开发组比较大时,势必会分布到不同的地理位置,若无法在同一个快速网络中工作,就会造成多个开发库并存的局面,这样就需要多个开发库结构的同步,甚至是开发测试数据的 ...

  7. Cocos2dx项目在各种IDE中新建类之后的可行编译方式

    注:这里说可行,但是并不是最好的,只是可以完成编译. 1.linux+code::blocks下的cocos2dx项目新建一个类TestScene.h 新建的TestScene.h和TestScene ...

  8. IE8下动态生成option无法设置文本内容

    问题: 1.在IE8下,JS动态添加 option 的时候,value 有值,但是文本内容添加不上 例:<option value="北京"></option&g ...

  9. Android 7.0 适配

    extends:http://www.jianshu.com/p/56b9fb319310http://blog.csdn.net/chay_chan/article/details/57083383

  10. Linux 的基本操作(系统的远程登录)

    系统的远程登录 首先要说一下,该部分内容对于linux初学者来讲并不是特别重要的,可以先跳过该章节,先学下一章,等学完后再回来看这一章. Linux大多应用于服务器,而服务器不可能像PC一样放在办公室 ...