asp.net使用MVC4框架基于NPOI做导出数据到Excel表
NPOI 是 POI 项目的 .NET 版本。POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。
使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。
下面我们使用NPOI在MVC4框架下制作一个导出的功能。
(1)在DAL数据访问层,定义需要需要导出的数据表,可以根据需要导出的字段,进行SQL语句的组织条件。
public DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ToString()))
{
string sql = "select [LoginID],[WageID],[Name],[UserLimit],[OnDutyTime],[CarShiFa],[OnDutyDay],[NightOnDuty],[AllNightOnDuty],[CarAllowance],[WorkOvertime],[WeekendNightWork],[WeekendOverNight] from Kaoqinsum where OnDutyTime=datename(yy,getdate()) + '-' + datename(m,dateadd(m,-1,getdate()))";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
conn.Close();
return dt;
}
}
(2)在BLL业务逻辑层,调用数据访问层中的GetDate();
public DataTable GetDate()
{
return new SalaryManageDAL.KaoqinsumDAL().GetData();
}
(3)在控制器中,我们来书写导出功能的主要代码。
public ActionResult DaoChu()
{
DataTable dt = new SalaryManageBLL.KaoqinsumBLL().GetDate();
//1、实例化workbook工作簿对象
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
//2、创建文档摘要信息
DocumentSummaryInformation dsf = PropertySetFactory.CreateDocumentSummaryInformation();
dsf.Company = "沈阳工学院";//公司
dsf.Category = "Statistics";//类别
//CustomProperties 自定义属性
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = "院办";//作者
//Comments 评论 CreateDateTime 创建时间 Template模板
si.Keywords = "kaoqin,yuanban";//关键字
si.Subject = "kaoqin";//主题
si.Title = "考勤汇总";//标题
si.RevNumber = "1.0";//版本号
//3、将写好的文档摘要 赋值workbook对象
hssfworkbook.DocumentSummaryInformation = dsf;
hssfworkbook.SummaryInformation = si;
//4、创建Sheet
HSSFSheet Sheet1 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet1");
HSSFSheet Sheet2 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet2");
HSSFSheet Sheet3 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet3");
//5、创建页眉页脚
Sheet1.CreateRow(0).CreateCell(1).SetCellValue(123); Sheet1.Header.Center = "统计数据";
Sheet1.Header.Left = "logo.png";
Sheet1.Header.Right = "zhguAddress";
Sheet1.Footer.Center = "page";
//6、标题
string yeartime = time(); HSSFCell fcell = (HSSFCell)Sheet1.CreateRow(0).CreateCell(0);//第一行
fcell.SetCellValue("沈阳工学院" + yeartime + "考勤汇总情况表");//文本
//合并单元格
Sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 13));//2.0使用 2.0以下为Region
//标题样式
HSSFCellStyle fCellStyle = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
HSSFFont ffont = (HSSFFont)hssfworkbook.CreateFont();
ffont.FontHeight = 20 * 20;
ffont.FontName = "宋体";
ffont.Color = HSSFColor.BLUE.index;
fCellStyle.SetFont(ffont);
fCellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;//垂直对齐
fCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;//水平对齐
fcell.CellStyle = fCellStyle; //7、设置单元格格式 创建单元格
/*模拟设定7列*/
HSSFDataFormat dataformat = (HSSFDataFormat)hssfworkbook.CreateDataFormat();//数据格式
HSSFFont font = (HSSFFont)hssfworkbook.CreateFont();//数据字体
font.Color = HSSFColor.BLACK.index; //颜色
font.IsItalic = false;//斜体
font.IsStrikeout = false;//加粗
font.FontName = "宋体";//字体 //必不可少 可以变更在循环输出数据时指定类型 需要调用sqlDbType 较复杂
//Id int类型
HSSFCell cell1 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(0); //创建单元格
HSSFCellStyle cellStyle1 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();//单元格样式
cellStyle1.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
// CellRangeAddressList ranglist1 = new CellRangeAddressList(0, 65535, 0, 0);//集合限定类型
// DVConstraint constraint1 = DVConstraint.CreateNumericConstraint(DVConstraint.ValidationType.INTEGER, DVConstraint.OperatorType.BETWEEN, "0", "100");//约束
cellStyle1.SetFont(font);
cell1.CellStyle = cellStyle1;
cell1.SetCellValue(""); //Name
HSSFCell cell2 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(1);
HSSFCellStyle cellStyle2 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle2.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle2.SetFont(font);
cell2.CellStyle = cellStyle2;
cell2.SetCellValue(""); //phone
HSSFCell cell3 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(2);
HSSFCellStyle cellStyle3 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle3.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle3.SetFont(font);
cell3.CellStyle = cellStyle3;
cell3.SetCellValue(""); //address
HSSFCell cell4 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(3);
HSSFCellStyle cellStyle4 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle4.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle4.SetFont(font);
cell4.CellStyle = cellStyle4;
cell4.SetCellValue(""); //Status
HSSFCell cell5 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(4);
HSSFCellStyle cellStyle5 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle5.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle5.SetFont(font);
cell5.CellStyle = cellStyle5;
cell5.SetCellValue(""); //balance
HSSFCell cell6 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(5);
HSSFCellStyle cellStyle6 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cell6.SetCellValue("");
cellStyle6.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle6.SetFont(font);
cell6.CellStyle = cellStyle6; //CreateDate
HSSFCell cell7 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(6);
HSSFCellStyle cellStyle7 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle7.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle7.SetFont(font);
cell7.CellStyle = cellStyle7;
cell7.SetCellValue(""); HSSFCell cell8 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(7);
HSSFCellStyle cellStyle8 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle8.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle8.SetFont(font);
cell8.CellStyle = cellStyle8;
cell8.SetCellValue(""); HSSFCell cell9 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(8);
HSSFCellStyle cellStyle9 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle9.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle9.SetFont(font);
cell9.CellStyle = cellStyle9;
cell9.SetCellValue(""); HSSFCell cell10 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(9);
HSSFCellStyle cellStyle10 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle10.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle10.SetFont(font);
cell10.CellStyle = cellStyle10;
cell10.SetCellValue(""); HSSFCell cell11 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(10);
HSSFCellStyle cellStyle11 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle11.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle11.SetFont(font);
cell11.CellStyle = cellStyle11;
cell11.SetCellValue(""); HSSFCell cell12 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(11);
HSSFCellStyle cellStyle12 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle12.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle12.SetFont(font);
cell12.CellStyle = cellStyle12;
cell12.SetCellValue(""); HSSFCell cell13 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(12);
HSSFCellStyle cellStyle13 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
cellStyle13.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
cellStyle13.SetFont(font);
cell13.CellStyle = cellStyle13;
cell13.SetCellValue(""); //8、创建单元格 加入数据
HSSFRow r = (HSSFRow)Sheet1.CreateRow(1);//第二行 标题
for (int i = 0; i < dt.Columns.Count; i++)
{
r.CreateCell(i).SetCellValue(dt.Columns[i].ToString());
}
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
HSSFRow row = (HSSFRow)Sheet1.CreateRow(i + 2);//写入行
for (int j = 0; j < dt.Columns.Count; j++)//写入列
{
if (dt.Columns[j].ColumnName == "balance")
{
row.CreateCell(j).CellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
row.CreateCell(j).SetCellValue(Convert.ToDouble(dt.Rows[i][j].ToString()));
}
else
{
row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
}
}
}
}
//9、求和 SUM函数
HSSFCell cesum = (HSSFCell)Sheet1.CreateRow(Sheet1.LastRowNum + 1).CreateCell(5);//最后一行+1行等于总计行
HSSFCell cebegin = (HSSFCell)Sheet1.GetRow(2).GetCell(5);//开始
HSSFCell ceend = (HSSFCell)Sheet1.GetRow(Sheet1.LastRowNum - 1).GetCell(5);//结束
cesum.SetCellFormula("sum(" + GetA_Z(5) + 3 + ":" + GetA_Z(5) + Sheet1.LastRowNum + ")");
FileStream fs = new FileStream(Server.MapPath("~/ExportFiles/" + yeartime + "考勤信息.xls"), FileMode.Create);
hssfworkbook.Write(fs);
fs.Close();
//Response.Write("导出完成");
return View();
//return ;
}
public string GetA_Z(double p)
{
string[] str = { "0:A", "1:B", "2:C", "3:D", "4:E", "5:F", "6:G", "7:H", "8:I", "9:J", "10:K", "11:L", "12:M", "13:N", "14:O", "15:P", "16:Q", "17:R", "18:S", "19:T", "20:U", "21:V", "22:W", "23:X", "24:Y", "25:Z" };
for (int i = 0; i < str.Length; i++)
{
if (p.ToString() == str[i].Split(':')[0].ToString())
{
return str[i].Split(':')[1].ToString();
}
}
return "";
}
由于实际项目中需要时间的条件限制。定义了一个返回值类型为string的time();
public String time()
{
string time = "";
DateTime dt = DateTime.Now;
int year = dt.Year;
int month = dt.Month;
if (1 < month && 10 > month)
{
time = year + "-";
time += "0";
time = time + Convert.ToString(month - 1);
}
if (month == 1)
{
year = dt.Year - 1;
time = Convert.ToString(year) + "-";
time += "12";
}
return time;
}
(4)在前台UI界面定义一个按钮,来实现点击触发控制器中的DaoChu();
<a href="#" id="daochu" class="easyui-linkbutton" data-options="iconCls:'icon-search'">导出数据</a>
定义id="daochu"所触发的事件。
  $("#daochu").click(function () {
                getdaochu = "/Kaoqinsum/DaoChu";
          //提交执行控制器的方法
                initDataGrid("#dg", colums, getdaochu);
          //创建个返回值日期,用于导出时对时间的判断,导出对应月份的数据。
                var date = new Date();
                var year = date.getFullYear();
                var month = date.getMonth();
                var clock;
                if (0 < month < 10) {
                    clock = year + "-";
                    clock += "0";
                    clock += month;
                }
                if (month == 0) {
                    year = date.getFullYear() - 1;
                    clock = year + "-";
                    clock += "12";
                }
                if ($("#OnDutyTime").datebox('getValue') != "") {
                    geturl3 = "../ExportFiles/" + $("#OnDutyTime").datebox('getValue') + "考勤信息.xls"; ;
                    window.open(geturl3);
                }
                if ($("#OnDutyTime").datebox('getValue') == "") {
                    geturl2 = "../ExportFiles/" + clock + "考勤信息.xls";
                    window.open(geturl2);
                }
            })
PS:导出的Excel表下载地址http://pan.baidu.com/s/1ntp2izn 密码:mxmo
asp.net使用MVC4框架基于NPOI做导出数据到Excel表的更多相关文章
- 使用npoi.dll导出数据到excel
		
.net数据导出excel数据有多种方法,最常用的就是使用office组件,但随之而来的问题也很棘手,又要调权限又要确定是否安装office很是麻烦,最近一个项目中也有数据导出功能,随使用excel模 ...
 - NPOI 通用导出数据到Excel                                                    分类:            C#             Helper             2014-11-04 16:06    246人阅读    评论(0)    收藏
		
应用场景: 在项目中,经常遇到将数据库数据导出到Excel,针对这种情况做了个程序封装.工作原理:利用NPOI将SQL语句查询出的DataTable数据导出到Excel,所见即所得. 程序界面: ...
 - 基于Open XML 导出数据到Excel
		
数据导出的结果: 步骤1.新建一个Excel 文档,模板根据自己需要设置 步骤2.使用OpenXml 打开Excel 文件 步骤3.点击ReflectCode 功能,生成相应的代码文档 using ...
 - NPOI导出数据到Excel
		
NPOI导出数据到Excel 前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微 ...
 - ASP导出数据到excel遇到的一些问题
		
一直用动易平台的ASP做新闻发布网站,直到现在才接触导出数据到Excel的问题,目的在于公司要统计各部门的投稿量,要做这么个东西,实现起来是挺简单的,但是第一次做,还是费了一些功夫的,特此记录一下 主 ...
 - 1.ASP.NET MVC使用EPPlus,导出数据到Excel中
		
好久没写博客了,今天特地来更新一下,今天我们要学习的是如何导出数据到Excel文件中,这里我使用的是免费开源的Epplus组件. 源代码下载:https://github.com/caofangshe ...
 - ASP.NET导出数据到Excel 实例介绍
		
ASP.NET导出数据到Excel 该方法只是把asp.net页面保存成html页面只是把后缀改为xlc不过excel可以读取,接下连我看看还有别的方式能导出数据,并利用模版生成. 下面是代码 新建 ...
 - ASP.NET 导出gridview中的数据到Excel表中,并对指定单元格换行操作
		
1. 使用NPOI读取及生成excel表. (1)导出Click事件: 获取DataTable; 给文件加文件名: string xlsxName = "xxx_" + DateT ...
 - 使用NPOI导入导出标准的Excel
		
关于NPOI NPOI是POI项目的.NET版本,是由@Tony Qu(http://tonyqus.cnblogs.com/)等大侠基于POI开发的,可以从http://npoi.codeplex. ...
 
随机推荐
- UITableView实现格瓦拉飞天投票模块
			
格瓦拉目前来说动画效果确实做的还比较好,虽然不是说很炫但做到精致,这次就模仿了它投票的模块.其实想到要实现它还是有很多方法,不过这次我还是采用了苹果自带控件UITableView简简单单来实现它,再次 ...
 - C  双向链表
			
单链表的结点都只有一个指向下一个结点的指针 单链表的数据元素无法直接访问其前驱元素 逆序访问单链表中的元素是极其耗时的操作! len = LinkList_Length(list); for (i=l ...
 - jni 之helloworld
			
前言: 作为android开发程序员,有的时候不得不和c,c++进行交互,有时候,需要把自己的应用加入一些特效,2d的或者3d的,特别是立志或者想要转向android游戏开发(目前所知,coc ...
 - 如何打开“USB调试”模式?
			
请首先确认您的系统版本, 点击「设置」-「关于手机」查看您当前的手机版本号. 如果您使用的是 Android 3.2及以下系统,请按以下步骤操作: STEP1:在应用列表选择「设置」进入系统设置菜单: ...
 - GCD多线程
			
GCD本质线程自动管理指令包 GCD优点: 1.GCD 本身自带有线程锁的效果,能通过推迟昂贵计算任务并在后台运行它们来改善应用的响应性能. 2.GCD 提供了更易于使用的并发模型(效果方面类似于对锁 ...
 - 3D分析之3D要素工具箱(转)
			
来自:http://blog.csdn.net/kikitamoon/article/details/8193764 整理有关 ArcGIS 10.1 3D分析工具箱中,3D Feature 工具箱中 ...
 - 关于XML的Schema文件讲解
			
1 Schema概述 1.1 什么是Schema l Schema是新的XML文档约束:DTD出现的比较早. l Schema要比DTD强大很多: l Schema本身也是XML文档,但Sche ...
 - vim纯文本处理插件txtbrowser
			
纯文本处理插件:txtBrowser 插件作者:http://guoyoooping.blog.163.com/ Github地址:https://github.com/vim-scripts/Txt ...
 - 使用SQL循环打印'*'菱形
			
菱形每一行都是由n个' ' + n 个'**' + 1个'*' 组成的 例如高度为9的菱形(共print 9次),*最多的一次print为第五次第五次就是0个' ' + 4个'**' + 1个'*' ...
 - 2014年下半年计划—写博客,旅游,带女朋友拍写真
			
前言:写这篇博客之前,一直在网上,看各位大牛写的博文,发布的视频等.当然由于自己的初来乍到,人生地不"熟"儿的,也吃了不少亏,走了不少弯路.本着一颗学习的心,携着向各 ...