/// <summary> /// 添加样式 /// </summary> /// <param name="sheet">excel工作簿</param> /// <param name="columns">总列数</param> /// <param name="globalStyle">全局样式</param> /// <param name="styles">样式</param> protected void AddStyle(ExcelWorksheet sheet, int columns, ExcelHeadStyle globalStyle = null, List <ExcelHeadStyle> styles = null) { var col = 0; if (styles != null) { foreach (var style in styles) { col++; if (col <= columns) { if (style.IsIgnore) { sheet.DeleteColumn(col); continue; } var excelCol = sheet.Column(col); if (!style.Format.IsNullOrWhiteSpace()) { excelCol.Style.Numberformat.Format = style.Format; } excelCol.Style.Font.Bold = style.IsBold; excelCol.Style.Font.Size = style.FontSize; if (style.IsAutoFit) { excelCol.AutoFit(); } } } } else { if (globalStyle != null) { for (var i = 1; i <= columns; i++) { if (globalStyle.IsIgnore) { sheet.DeleteColumn(i); continue; } var excelCol = sheet.Column(i); if (!globalStyle.Format.IsNullOrWhiteSpace()) { excelCol.Style.Numberformat.Format = globalStyle.Format; } excelCol.Style.Font.Bold = globalStyle.IsBold; excelCol.Style.Font.Size = globalStyle.FontSize; if (globalStyle.IsAutoFit) { excelCol.AutoFit(); } } } } }
/// <summary> /// 导出excel表头 /// </summary> /// <param name="items">表头数组</param> /// <param name="sheetName">工作簿名称</param> /// <param name="globalStyle">全局样式</param> /// <param name="styles">样式</param> /// <returns></returns> public Task <byte[]> ExportHeaderAsByteArray(string[] items, string sheetName, ExcelHeadStyle globalStyle = null, List <ExcelHeadStyle> styles = null) { using (var excelPackage = new ExcelPackage()) { var sheet = excelPackage.Workbook.Worksheets.Add(sheetName ?? "导出结果"); sheet.OutLineApplyStyle = true; AddHeader(items, sheet); AddStyle(sheet, items.Length, globalStyle, styles); return(Task.FromResult(excelPackage.GetAsByteArray())); } }