使用NPOI完成导出Excel文件
参考网址: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文件的更多相关文章
- C#,使用NPOI,导出excel文件
/// <summary> /// 导出excel文件 /// </summary> /// <param name="dt">Table表数据 ...
- html+ashx + NPOI 实现导出Excel文件并且预览和下载
先看看实现效果 简单描述一下实现过程: 1. 生成报表,返回报表文件路径 $.post 请求一般处理文件ashx ,通过npoi生成对应的excel文件.生成成功后,返回文件保存的完整路径 2. ...
- 简单回顾NPOI导入导出excel文件
当前环境.net4.0 去官方下下载: NOPI官网 关于NOPI的详细,这里就不再介绍. 在项目中,我们只需引入 NPOI.dll 就可以了. 接下来..................... ...
- 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的路由方案,与原来的方案在使用上差别不 ...
- 关于NPOI导出excel文件(xls和xlsx两种格式)提示格式不符的问题
这两天在做导出excel文件的时候遇到这个问题 本来我导出的格式是xlsx格式的,但是下载得到的文件格式变成了xls, 一开始以为是返回的contenttype设置错了 return File(ms, ...
- 基于Vue + axios + WebApi + NPOI导出Excel文件
一.前言 项目中前端采用的Element UI 框架, 远程数据请求,使用的是axios,后端接口框架采用的asp.net webapi,数据导出成Excel采用NPOI组件.其业务场景,主要是列表页 ...
- 使用NPOI或EPPlus来导出Excel文件实例,可在Excel文件加密
使用NPOI.dll组件来导出Excel文件,并设置样式,Nuget引用即可. packages\NPOI.2.1.3.1\lib\net20\NPOI.dll #region Excel prote ...
- 使用NPOI导出Excel文件
使用NPOI导出Excel文件,本实例使用了ASP.NET MVC. 1.使用NPOI导出Excel文件 实例:导出商品列表. 要求:1.通过NPOI导出导出商品列表信息: 2.使用Excel函数计算 ...
- NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中
以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...
随机推荐
- Android添加权限大讲解
对于新手来说,最烦恼的不是如何从网上下载到安卓项目,而是下载到的安卓项目不知道如何添加权限和要添加哪些权限. 现在就针对安卓的权限来讲解这些权限应该具体用在什么地方 首先在项目下找到 AndroidM ...
- 优化Linux下的内核TCP参数来提高服务器负载能力
http://blog.renhao.org/2010/07/setup-linux-kernel-tcp-settings/ /proc/sys/net目录 所有的TCP/IP参数都位于/proc/ ...
- IIS6 + PHP 访问页面出现:需要进行身份验证的问题
问题描述:之前在IIS6上安装了PHP扩展,发布了一个PHP网站可以正常访问,为了测试网站并发量修改了一个PHP的配置文件以后,再访问就弹出 需要用户名和密码. 同一目录下的 aspx文件可以正常访问 ...
- Centos6.5系统初学者基本系统配置1
作为一个初步接触linux-Centos的菜鸟来说,Centos在基本软件安装是一件比较令人头疼的事情,下面我将我初步使用linux的一些问题进行了汇总和记录,希望对大家有所帮助,这些东西也是在网友的 ...
- Spring Controller 获取请求参数的几种方法
1.直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交.若"Content-Type"="application/ ...
- 前端代码优化: 使用YUI Compressor
通过压缩组件,可以显著减少HTTP请求和响应事件.这也是减小页面大小最简单的技术,但也是效果最明显的. 压缩JS,CSS代码有几种常用插件,YUI Compressor是个不错的选择.通过maven的 ...
- ie使用firebug
在网页插入以下代码即可. <script type="text/javascript" src="http://getfirebug.com/releases/li ...
- C#局域网桌面共享软件制作(三)
到周末了,继续做这个桌面共享软件,下面是前两篇的链接, 链接 C#局域网桌面共享软件制作(一) 链接 C#局域网桌面共享软件制作(二) 通过对图片进行压缩以后,每张图片大小38K左右(win7/102 ...
- 代码快捷键的设置读取App.config方法
附件下载:http://files.cnblogs.com/files/qtiger/ShortcutAchieve.zip 代码实现最重要(增加引用using System.Configuratio ...
- 两个和尚抬水有水喝,三个和尚抬水没水喝------IT项目管理之组织架构
说到项目经理岗位,一般的想法是,一个项目只能有一个项目经理,否则责任不明,互相推诿.偏偏IT项目需要有两个甚至三个项目经理.原因何在呢? 典型的IT项目(不包含纯技术或工具类项目)是把用户的需求转化成 ...