function getExcelToPage() {
var grid = $("#tb1");
var options = grid.datagrid('getPager').data("pagination").options;
//当前页
var curr = options.pageNumber;
$.ajax({
url: "/Handlers/DataMan/Handler1.ashx?action=getExPage",
data: {
index: curr
},
beforeSend: function () {//ajax执行之前运行
//打开进度条
var win = $.messager.progress({
title: '文件下载中,请耐心等待.....',//标题
msg: 'Loading data...'//消息框显示值
});
},
complete: function () {//ajax执行之后,且不论结果是成功还是失败
$.messager.progress("close");
},
success: function (res) {
var link = document.createElement('a');//创建a标签
link.setAttribute("download", "");//实现下载
link.href = res;//下载地址
link.click();
}
});
}
public void ExcelPaege(HttpContext context)
{
try
{
int pageSize = 10;
if (!String.IsNullOrEmpty(context.Request["rows"]))
{
pageSize = int.Parse(context.Request["rows"].ToString());
}
int pageIndex = Convert.ToInt32(context.Request["index"]);
if (!string.IsNullOrEmpty(context.Request["page"]))
{
pageIndex = int.Parse(context.Request["page"]);
}
int countPage = 0;
string where = "";
string order = "asc";
if (!string.IsNullOrEmpty(context.Request["order"]))
{
order = context.Request["order"];
}
string sort = "编号";
if (!string.IsNullOrEmpty(context.Request["sort"]))
{
sort = context.Request["sort"];
}
DataTable dt = bll.SelectList(where, pageSize, pageIndex, sort, order, out countPage);
string excel = Common.ExcelHelper.ExportEasy(dt, context);
context.Response.Write(excel);
}
catch (Exception ex)
{
throw ex;
}
}
public class ExcelHelper
{
public static string ExportEasy(DataTable dtSource, HttpContext context)
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0);
foreach (DataColumn column in dtSource.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
for (int i = 0; i < dtSource.Rows.Count; i++)
{
dataRow = (HSSFRow)sheet.CreateRow(i + 1);
for (int j = 0; j < dtSource.Columns.Count; j++)
{
dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
}
}
string strFileName = context.Server.MapPath("~/") + @"\MyExc\excel.xls";
string url = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + "/MyExc/excel.xls";
using (MemoryStream ms = new MemoryStream())
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}
return url;
}
}