/// <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();
}