• C# 导出数据到Excel


    后台代码

    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("网络错误,请稍后重试");
            }
        });
    }
  • 相关阅读:
    Qt调用外部程序QProcess通信
    QT错误:collect2:ld returned 1 exit status
    ARM编译空间属性(转)
    深入C语言内存区域分配(进程的各个段)详解(转)
    Linux系统的组成和内核的组成
    C语言中,头文件和源文件的关系(转)
    Ubuntu安装samba服务器
    2018年应该做的事
    生活经历1
    学习笔记
  • 原文地址:https://www.cnblogs.com/xiaonangua/p/11737858.html
Copyright © 2020-2023  润新知