[HttpGet]
public async Task<ActionResult> DownTestFile(RedScarfBadgeManage.Dto.RedScarfBadgeStudentListByConditionInput input)
{
using (var client = new WebClient())
{
byte[] bytes =await _RedScarfBadgeManageAppService.ExportRedScarfBadgeStudentListByConditionToExcel(input);
return File(bytes, "application/octet-stream", "ceshi.xlsx");
}
}
MemoryStream stream = new MemoryStream();
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Test");
worksheet.OutLineApplyStyle = true;
//添加表头
worksheet.Cells[1, 1].Value = "学校";
worksheet.Cells[1, 1].Style.Font.Bold = true;
worksheet.Cells[1, 2].Value = "年级";
worksheet.Cells[1, 2].Style.Font.Bold = true;
worksheet.Cells[1, 3].Value = "班级";
worksheet.Cells[1, 3].Style.Font.Bold = true;
worksheet.Cells[1, 4].Value = "登录账号";
worksheet.Cells[1, 4].Style.Font.Bold = true;
worksheet.Cells[1, 5].Value = "学生姓名";
worksheet.Cells[1, 5].Style.Font.Bold = true;
worksheet.Cells[1, 6].Value = "奖章总数";
worksheet.Cells[1, 6].Style.Font.Bold = true;
worksheet.Cells[2, 1].Value = "学校";
worksheet.Cells[2, 1].Style.Font.Bold = true;
worksheet.Cells[2, 2].Value = "年级";
worksheet.Cells[2, 2].Style.Font.Bold = true;
worksheet.Cells[2, 3].Value = "班级";
worksheet.Cells[2, 3].Style.Font.Bold = true;
worksheet.Cells[2, 4].Value = "登录账号";
worksheet.Cells[2, 4].Style.Font.Bold = true;
worksheet.Cells[2, 5].Value = "学生姓名";
worksheet.Cells[2, 5].Style.Font.Bold = true;
worksheet.Cells[2, 6].Value = "奖章总数";
worksheet.Cells[2, 6].Style.Font.Bold = true;
//合并列(开始行,开始列,结束行,结束列)
MergeColCells(worksheet, 1, 1, 2, 1);
MergeColCells(worksheet, 1, 2, 2, 2);
MergeColCells(worksheet, 1, 3, 2, 3);
MergeColCells(worksheet, 1, 4, 2, 4);
MergeColCells(worksheet, 1, 5, 2, 5);
MergeColCells(worksheet, 1, 6, 2, 6);
var i = 7;
var j = 0;
foreach (var m in cList)
{
j = i;
foreach (var n in m.BadgeChildDto)
{
worksheet.Cells[1, i].Value = m.ChapterTypeName;
worksheet.Cells[1, i].Style.Font.Bold = true;
worksheet.Cells[2, i].Value = n.BadgeName;
worksheet.Cells[2, i].Style.Font.Bold = true;
i++;
}
MergeColCells(worksheet, 1, j, 1, i-1);
}
package.Save();
}
return stream.GetBuffer();
/// <summary>
/// 合并单元格
/// </summary>
/// <param name="sheet"></param>
public static void MergeColCells(ExcelWorksheet sheet, int fromRow, int fromCol,int toRow,int toCol)
{
sheet.Cells[fromRow,fromCol,toRow,toCol].Merge = true;
sheet.Cells[fromRow, fromCol, toRow, toCol].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
sheet.Cells[fromRow, fromCol, toRow, toCol].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
引用:https://www.cnblogs.com/jishugaochao/p/10344912.html