导出excel,怎么导出呢?这个原理是什么呢?
首先在html页面添加单击方法,触发controllers中的方法。怎么触发controllers中导出的方法呢?
在js中的事件中可以这样写。
function xport() {
window.location.href = "/UserManager/OutoExcel";
}
大家也知道OutoExcel就是contrlers中导出的方法了。
其实导出的数据,不是像机房收费系统中从ui表格中得到数据。这个是怎么做呢?举一个例子,查询所有的用户,查到的结果用一个list来接收,然后在返回到js中显示到html页面中。现在把list变成staic类型的。成了静态全局变量。
这样在调用这个list给excel的各个表格赋值,这样excel就做好了。重要的事情就是list要变成静态全局变量。
来看一下controllers的代码。
public void OutoExcel() {
try
{
string title = "人员信息统计";
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");
NPOI.SS.UserModel.IRow headerrow = sheet.CreateRow(0);
ICellStyle style = book.CreateCellStyle();
// HorizontalAlignment.Center;
style.Alignment = HorizontalAlignment.Center;
style.VerticalAlignment = VerticalAlignment.Center;
#region 表格标题设置 表格的表头
ICell cell = headerrow.CreateCell(0);
cell.CellStyle = style;
cell.SetCellValue("用户账号");
cell = headerrow.CreateCell(1);
cell.CellStyle = style;
cell.SetCellValue("级别");
cell = headerrow.CreateCell(2);
cell.CellStyle = style;
cell.SetCellValue("姓名");
cell = headerrow.CreateCell(3);
cell.CellStyle = style;
cell.SetCellValue("电话");
cell = headerrow.CreateCell(4);
cell.CellStyle = style;
cell.SetCellValue("邮箱");
cell = headerrow.CreateCell(5);
cell.CellStyle = style;
cell.SetCellValue("备注");
//cell = headerrow.CreateCell(6);
//cell.CellStyle = style;
//cell.SetCellValue("操作列");
#endregion
#region 根据标题for循环填充excel表格
for (int i = 0; i < list.Count; i++)
{
IRow row = sheet.CreateRow(i + 1);
cell = row.CreateCell(0);
cell.SetCellValue(list[i].Userid.ToString());
cell = row.CreateCell(1);
cell.SetCellValue(list[i].Commentid.ToString()); //关键在于list list设置成了静态变量(可以理解成全局变量)
cell = row.CreateCell(2);
cell.SetCellValue(list[i].Username.ToString());
cell = row.CreateCell(3);
cell.SetCellValue(list[i].Tel.ToString());
cell = row.CreateCell(4);
cell.SetCellValue(list[i].Mail.ToString());
cell = row.CreateCell(5);
cell.SetCellValue(list[i].Remark.ToString());
//cell = row.CreateCell(6);
//cell.SetCellValue(list[i].);
}
#region 导出
//弹出导出的界面
MemoryStream ms = new MemoryStream();
book.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", title + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8));
Response.BinaryWrite(ms.ToArray());
Response.End();
book = null;
ms.Close();
ms.Dispose();
#endregion
#endregion
}
catch (Exception)
{
throw new Exception("导出遇到错误,请联系管理员");
}
}
其中,NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");
NPOI.SS.UserModel.IRow headerrow = sheet.CreateRow(0); 这段代码的使用需要使用引入命名空间。
using System.IO;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
其中还需要引用NPOI 2.2.1 binary package的几个dll。才能在命名空间上写出。下载地址 http://npoi.codeplex.com/downloads/get/1476595