参考网址:http://blog.csdn.net/tiemufeng1122/article/details/6732588

能够实现  点击按钮弹出下载框    的功能,如图:

HTML代码:

  <button type="button" class="bk-margin-5 btn btn-success" onclick="printExcel()">Excel导出</button>

 <script type="text/javascript">
function printExcel() {
post("PrintExcel", null); //如果调用时有参数,则post("PrintExcel",{id:id});
}
function post(URL, PARAMS) {
var temp = document.createElement("form");
temp.action = URL;
temp.method = "post";
temp.style.display = "none";
for (var x in PARAMS) {
var opt = document.createElement("textarea");
opt.name = x;
opt.value = PARAMS[x];
temp.appendChild(opt);
}
document.body.appendChild(temp);
temp.submit();
return temp;
}
</script>

后台代码:

  [HttpPost]//只接受post请求
public void PrintExcel()
{
//接收参数 int id=Int32.Parse(Requert.Form["id"]);
string trainShift = Session["trainshiftNum"].ToString();
#region 转换成DataSet
var query = from s in db.Students
where s.IsDelete == false && s.TrainShiftNum == trainShift
select new Stu
{
StudentDepartment = s.StudentDepartment,
StudentGender = s.StudentGender,
StuDentIdCard = s.StuDentIdCard,
StudentName = s.StudentName,
StudentNation = s.StudentNation,
StudentPosition = s.StudentPosition,
StudentUnit = s.StudentUnit,
TrainShiftNum = s.TrainShiftNum,
Remark = s.Remark
};
DataTable dt = query.ToDataTable(rec => new object[] { query });//调用转换DataTable方法 #endregion HSSFWorkbook book = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
ISheet sheet = book.CreateSheet("sheet1"); // 首列
NPOI.SS.UserModel.IRow row = sheet.CreateRow();
row.CreateCell().SetCellValue("序号");
row.CreateCell().SetCellValue("所在单位");
row.CreateCell().SetCellValue("所在部门");
row.CreateCell().SetCellValue("姓名");
row.CreateCell().SetCellValue("职务");
row.CreateCell().SetCellValue("性别");
row.CreateCell().SetCellValue("民族");
row.CreateCell().SetCellValue("出生年月");
row.CreateCell().SetCellValue("组");
row.CreateCell().SetCellValue("备注");
#region
//// 第一列
//NPOI.SS.UserModel.IRow row1 = sheet.CreateRow(1);
//row1.CreateCell(0).SetCellValue("所在单位"); //// 第二列
//NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(2);
//row2.CreateCell(0).SetCellValue("所在部门"); //// 第三列
//NPOI.SS.UserModel.IRow row3 = sheet.CreateRow(3);
//row3.CreateCell(0).SetCellValue("姓名"); //// 第四列
//NPOI.SS.UserModel.IRow row4 = sheet.CreateRow(4);
//row4.CreateCell(0).SetCellValue("职务"); //// 第五列
//NPOI.SS.UserModel.IRow row5 = sheet.CreateRow(5);
//row5.CreateCell(0).SetCellValue("性别"); //// 第六列
//NPOI.SS.UserModel.IRow row6 = sheet.CreateRow(6);
//row6.CreateCell(0).SetCellValue("民族"); //// 第七列
//NPOI.SS.UserModel.IRow row7 = sheet.CreateRow(7);
//row7.CreateCell(0).SetCellValue("出生年月"); //// 第八列
//NPOI.SS.UserModel.IRow row8 = sheet.CreateRow(8);
//row8.CreateCell(0).SetCellValue("组"); //// 第九列
//NPOI.SS.UserModel.IRow row9 = sheet.CreateRow(9);
//row9.CreateCell(0).SetCellValue("备注");
#endregion
int rowIndex = ; foreach (DataRow r in dt.Rows)
{
NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
string str = r["StuDentIdCard"].ToString().Substring(, );
str = str.Substring(, ) + "-" + str.Substring(, ) + "-" + str.Substring(, );
dataRow.CreateCell().SetCellValue(rowIndex.ToString());
dataRow.CreateCell().SetCellValue(r["StudentUnit"].ToString());
dataRow.CreateCell().SetCellValue(r["StudentDepartment"].ToString());
dataRow.CreateCell().SetCellValue(r["StudentName"].ToString());
dataRow.CreateCell().SetCellValue(r["StudentPosition"].ToString());
dataRow.CreateCell().SetCellValue(r["StudentGender"].ToString() == "" ? "男" : "女");
dataRow.CreateCell().SetCellValue(r["StudentNation"].ToString());
dataRow.CreateCell().SetCellValue(str);
dataRow.CreateCell().SetCellValue(r["TrainShiftNum"].ToString());
dataRow.CreateCell().SetCellValue(r["Remark"].ToString());
rowIndex++;
} // 写入到客户端
book.Write(ms);
//Response.ClearContent();
//Response.Clear();
//Response.Buffer = true;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", System.DateTime.Now.ToString("yyyymmddhhmmss")));
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
Response.BinaryWrite(ms.ToArray());
book = null;
ms.Close();
ms.Dispose();
}

转换DataTable的代码(在网上查到的完美转换法,注意的是怎么调用):

  public static class ListToDataTable  //可以直接使用
{
public static DataTable ToDataTable<T>(this IEnumerable<T> varlist, CreateRowDelegate<T> fn)
{ DataTable dtReturn = new DataTable(); // column names PropertyInfo[] oProps = null; // Could add a check to verify that there is an element 0 foreach (T rec in varlist)
{ // Use reflection to get property names, to create table, Only first time, others will follow if (oProps == null)
{ oProps = ((Type)rec.GetType()).GetProperties(); foreach (PropertyInfo pi in oProps)
{ Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{ colType = colType.GetGenericArguments()[]; } dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); } } DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps)
{ dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null); } dtReturn.Rows.Add(dr); } return (dtReturn); } public delegate object[] CreateRowDelegate<T>(T t); }

还有就是类的写法:

   /// <summary>
/// 打印学员名单
/// </summary>
public class Stu
{
private string studentUnit; public string StudentUnit
{
get { return studentUnit; }
set { studentUnit = value; }
}
private string studentDepartment; public string StudentDepartment
{
get { return studentDepartment; }
set { studentDepartment = value; }
}
private string studentName; public string StudentName
{
get { return studentName; }
set { studentName = value; }
}
private string studentPosition; public string StudentPosition
{
get { return studentPosition; }
set { studentPosition = value; }
}
private int studentGender; public int StudentGender
{
get { return studentGender; }
set { studentGender = value; }
}
private string studentNation; public string StudentNation
{
get { return studentNation; }
set { studentNation = value; }
}
private string stuDentIdCard; public string StuDentIdCard
{
get { return stuDentIdCard; }
set { stuDentIdCard = value; }
}
private string trainShiftNum; public string TrainShiftNum
{
get { return trainShiftNum; }
set { trainShiftNum = value; }
}
private string remark; public string Remark
{
get { return remark; }
set { remark = value; }
}
}

结果如图:

使用NPOI完成导出Excel文件的更多相关文章

  1. C#,使用NPOI,导出excel文件

    /// <summary> /// 导出excel文件 /// </summary> /// <param name="dt">Table表数据 ...

  2. html+ashx + NPOI 实现导出Excel文件并且预览和下载

      先看看实现效果 简单描述一下实现过程: 1. 生成报表,返回报表文件路径 $.post 请求一般处理文件ashx ,通过npoi生成对应的excel文件.生成成功后,返回文件保存的完整路径 2.  ...

  3. 简单回顾NPOI导入导出excel文件

    当前环境.net4.0 去官方下下载:  NOPI官网 关于NOPI的详细,这里就不再介绍. 在项目中,我们只需引入  NPOI.dll  就可以了. 接下来..................... ...

  4. ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案 try.dot.net 的正确使用姿势 .Net NPOI 根据excel模板导出excel、直接生成excel .Net NPOI 上传excel文件、提交后台获取excel里的数据

    ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案   ASP.NET Core 从2.2版本开始,采用了一个新的名为Endpoint的路由方案,与原来的方案在使用上差别不 ...

  5. 关于NPOI导出excel文件(xls和xlsx两种格式)提示格式不符的问题

    这两天在做导出excel文件的时候遇到这个问题 本来我导出的格式是xlsx格式的,但是下载得到的文件格式变成了xls, 一开始以为是返回的contenttype设置错了 return File(ms, ...

  6. 基于Vue + axios + WebApi + NPOI导出Excel文件

    一.前言 项目中前端采用的Element UI 框架, 远程数据请求,使用的是axios,后端接口框架采用的asp.net webapi,数据导出成Excel采用NPOI组件.其业务场景,主要是列表页 ...

  7. 使用NPOI或EPPlus来导出Excel文件实例,可在Excel文件加密

    使用NPOI.dll组件来导出Excel文件,并设置样式,Nuget引用即可. packages\NPOI.2.1.3.1\lib\net20\NPOI.dll #region Excel prote ...

  8. 使用NPOI导出Excel文件

    使用NPOI导出Excel文件,本实例使用了ASP.NET MVC. 1.使用NPOI导出Excel文件 实例:导出商品列表. 要求:1.通过NPOI导出导出商品列表信息: 2.使用Excel函数计算 ...

  9. NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中

    以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...

随机推荐

  1. cocos2dx 内存管理机制

    持续更新吧. 刚开始看了一些. 一,CCObject  提供引用计数 1,unsinged int m_uReference; //此为CCOBject的引用计数,初始化为 1: new CCObje ...

  2. Python之路【第五篇】:面向对象及相关

    Python之路[第五篇]:面向对象及相关   面向对象基础 基础内容介绍详见一下两篇博文: 面向对象初级篇 面向对象进阶篇 其他相关 一.isinstance(obj, cls) 检查是否obj是否 ...

  3. 使用HTML5构建下一代的Web Form

    HTML语言作为如今编程最为广泛的语言,具有易用.快捷.多浏览平台兼容等特点,但是随着时代的进步,HTML的标准却停滞不前,这一次还在不断开发中的[color=#444444 !important]H ...

  4. ubuntu12.04 下安装matlab2012

    1.下载matlab2012a(例如:****.iso) 2.创建挂载目录 sudo mkdir /media/matlab 3.将当前目录切换到镜像文件的目录,然后将镜像文件挂载到刚刚创建的目录下 ...

  5. 调试工具-fiddler

    本地资源替换线上调试 Fiddler是一个http协议调试代理工具,它能够记录并检查所有你的电脑和互联网 之间的http通讯,设置断点,查看所有的“进出”Fiddler的数据(指cookie,html ...

  6. Silverlight - GPU加速

    1. 在Silverlight plug-in上设置 <param name="enableGPUAcceleration" value="true" / ...

  7. Java通过Executors提供四种线程池

    http://cuisuqiang.iteye.com/blog/2019372 Java通过Executors提供四种线程池,分别为:newCachedThreadPool创建一个可缓存线程池,如果 ...

  8. PHP字符串拼接与MySQL语句

    这个部分总是钻牛角尖.总是出错. public function getList($pagesize=25){ $where = '1'; $tableName = $this->getTabl ...

  9. mysql 修改字段长度

    mysql 修改字段长度 alter table news  modify column title varchar(130); alter table 表名 modify column 字段名 类型 ...

  10. slidingmenu

        slidingmenu是一个开源组件.提供了左滑菜单和右滑菜单.下面是一个使用例子的工程源码.     在项目中不去管源码仅仅只是使用的话,主要需要实现的有3个类 MainActivity:这 ...