.net Core NPOI 下载为excel

 [HttpPost]
        public FileResult ExportXlsx(string title, string name, string ps)
        {
            try
            {
                title = System.Web.HttpUtility.UrlDecode(title);
                name = System.Web.HttpUtility.UrlDecode(name);
                ps = System.Web.HttpUtility.UrlDecode(ps);
                string data = OpenController.getCache(name, ps, cacheMinutes);
                DataTable dt = JsonToDataTable(data);
                XSSFWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = null;

                int headRowIndex = 0;
                string sheetName = "Sheet1";
                if (!string.IsNullOrEmpty(dt.TableName))
                {
                    sheetName = dt.TableName;
                }
                sheet = workbook.CreateSheet(sheetName);
                int rowIndex = 0;

                #region 列头及样式
                {
                    XSSFRow headerRow = (XSSFRow)sheet.CreateRow(headRowIndex);

                    ICellStyle headStyle = workbook.CreateCellStyle();
                    headStyle.Alignment = HorizontalAlignment.Center;
                    IFont font = workbook.CreateFont();
                    font.FontHeightInPoints = 10;
                    font.Boldweight = 700;
                    headStyle.SetFont(font);

                    foreach (DataColumn column in dt.Columns)
                    {
                        headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                        headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
                    }
                }
                #endregion

                #region 填充内容

                foreach (DataRow row in dt.Rows)
                {
                    rowIndex++;
                    XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in dt.Columns)
                    {
                        string drValue = row[column].ToString();
                        dataRow.CreateCell(column.Ordinal).SetCellValue(drValue);
                    }
                }
                #endregion

               

            //项目中应该改为相对路径而不是绝对路径 //因不知道用户的excel版本所以生成文件后缀为.xls,因为2003版的excel后缀名为.xls,2007版后均为.xlsx
                string filename = title + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
                string path = _hostingEnvironment.WebRootPath + @"\sys_manage\report\download\"+filename;
                using (FileStream file = new FileStream(path, FileMode.Create))//创建文件流,将灌好数据的excel文件写入服务器的硬盘
               {
                    workbook.Write(file);
                }
                return File(new FileStream(path, FileMode.Open), "application/ms-excel", filename);//提示用户下载服务器上的文件

            }

            catch (Exception ex)
            {
                return null;
                //   return Json(new { code = "-1", message = ex.Message });
                //    return Json(new { code = "-1", message = ex.Message });
            }







        }

 

js端:

 



var DownLoadFile = function (options) {
    var config = $.extend(true, { method: 'post' }, options);
    var $iframe = $('<iframe id="down-file-iframe" />');
    var $form = $('<form target="down-file-iframe" method="' + config.method + '"  enctype="multipart/form-data"/>');
    $form.attr('action', config.url);
    for (var key in config.data) {
        //  if (key != 'data')
        $form.append('<input type="hidden" name="' + key + '" value="' + escape(config.data[key])/*.replace('"[', '[').replace(']"',']').replace(reg,'\'')*/ + '" />');
        //  else
        //     $form.append("file", fso);// 文件对象   

    }
    $iframe.append($form);
    $(document.body).append($iframe);
    $form[0].submit();
    $iframe.remove();
}

 

var tableDl = function (title, proc, ps) {
    DownLoadFile({
   //     url: "/sys_manage/report/Download/downloadInit",
        url: "/sys_manage/report/Download/ExportXlsx",
        data: { "title": title, "name": proc, "ps": JSON.stringify(ps) }//要发送的数据
    });

};

posted @ 2018-10-23 10:21  KJXY  阅读(786)  评论(0)    收藏  举报