后台代码

public ActionResult ExportUserInfo()
{
    HSSFWorkbook hssfworkbook = new HSSFWorkbook();
    #region 定义excel表格
    ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
    IRow row = sheet1.CreateRow(0);
    //设置列宽度
    sheet1.SetColumnWidth(0, 20 * 256);
    sheet1.SetColumnWidth(1, 30 * 256);

    IRow row1 = sheet1.CreateRow(0);
    row1.CreateCell(0).SetCellValue("姓名");
    row1.CreateCell(1).SetCellValue("性别");
    #endregion

    #region 填充数据
    int rownum = 1;
    var list = new List<UserInfo>(){new UserInfo(){Name="小明",Sex=""},new UserInfo(){Name="小红",Sex=""};}
    if (!list.Any()) return Json(new { result = false, msg = "没有错误数据" });
    foreach (var model in list)
    {
        IRow row3 = sheet1.CreateRow(rownum);
        row3.CreateCell(0).SetCellValue(model.Name);
        row3.CreateCell(1).SetCellValue(model.Sex);
        rownum++;
    }

    #endregion

    string folder = Server.MapPath("/Down/");
    if (!Directory.Exists(folder))
    {
        Directory.CreateDirectory(folder);
    }
    //写入到表格
    string filename2 = "用户信息" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
    using (FileStream fs = new FileStream(folder + filename2, FileMode.OpenOrCreate, FileAccess.Write))
    {
        hssfworkbook.Write(fs);
    }

    string url = "../Down/" + filename2;
    return Json(new { result = true, url = url });
}

前台代码

//导出用户信息
function ExportUserInfos() {
    $.ajax({
        url: '/UserInfo/ExportUserInfo',
        type: 'post',
        cache: false,
        success: function (json) {
            if (json.result)
                window.location.href = json.url;
            else
               alert("没有数据!");
        }, error: function () {
            alert("网络错误,请稍后重试");
        }
    });
}
01-05 04:25