api将datatable导成Excel

/// <summary>
        /// 下载报名信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("api/admin/RegistAPI/ExportRegistData")]
        //接口导出文件流
        public HttpResponseMessage ExportRegistData(string activityId)
        {
            try
            {
                System.Data.DataTable dt = registService.GetRegistExportData(activityId);
                if (dt == null || dt.Rows.Count <= 0)
                {
                    return new HttpResponseMessage()
                    {
                        Content = new StringContent(JsonConvert.SerializeObject(new ResultInfo()
                        {
                            Data = "",
                            Msg = "没有报名数据可下载",
                            Success = false
                        }), System.Text.Encoding.GetEncoding("UTF-8"), "application/json")
                    };
                }
                ActivityService activityService = new ActivityService();
                string fileName = activityService.GetActivityName(activityId);
                var result = DownLoadHelper.Export(dt);
                var browser = String.Empty;
                fileName = fileName + DateTime.Now.ToString("yyMMddHH") + ".xlsx";
                if (HttpContext.Current.Request.UserAgent != null)
                {
                    browser = HttpContext.Current.Request.UserAgent.ToUpper();
                }
                HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
                Stream stream = new MemoryStream(result);
                httpResponseMessage.Content = new StreamContent(stream, result.Length);
                httpResponseMessage.Content.Headers.ContentLength = stream.Length;
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // 返回类型必须为文件流 application/octet-stream 
                httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") // 设置头部其他内容特性, 文件名 
                {
                    FileName = browser.Contains("FIREFOX") ? fileName : HttpUtility.UrlEncode(fileName)
                };
                httpResponseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

                return httpResponseMessage;
            }
            catch (Exception ex)
            {
                log.SaveLog(ex.ToString());
                return new HttpResponseMessage()
                {
                    Content = new StringContent(JsonConvert.SerializeObject(new ResultInfo()
                    {
                        Data = "",
                        Msg = "下载失败",
                        Success = false
                    }), System.Text.Encoding.GetEncoding("UTF-8"), "application/json")
                };
            }
        }

 

public static byte[] Export(DataTable dt)
        {
            var workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet();

            var headerStyle = workbook.CreateCellStyle(); //Formatting
            var headerFont = workbook.CreateFont();
            headerFont.IsBold = true;
            headerFont.FontHeightInPoints = 12;
            headerStyle.SetFont(headerFont);

            var header = sheet.CreateRow(0);
            for (var i = 0; i < dt.Columns.Count; i++)
            {
                var cell = header.CreateCell(i);
                string val = dt.Columns[i].Caption ?? dt.Columns[i].ColumnName;
                cell.SetCellValue(val);
                cell.CellStyle = headerStyle;
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow excelRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    excelRow.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j]));
                }
            }

            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            return ms.ToArray();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值