.NET 6中使用ClosedXML导出Excel格式异常问题求助
问题:ClosedXML导出Excel格式不符合预期
预期格式说明
- 表头:浅蓝色背景、加粗文字、居中对齐、带筛选功能
- 数据行:交替浅灰色背景、所有单元格带细边框、列宽自适应内容
- 数据格式:保留原始类型(如日期、数字),不强制转为字符串
实际导出问题
- 表头筛选重复设置导致异常
- 交替行背景颜色逻辑错误
- 缺少单元格边框
- 所有数据被强制转为字符串,丢失原有格式
- 表头未设置居中对齐
修正后的导出代码
using ClosedXML.Excel; using System.Data; namespace GlobalClass.HelperClass { public class ExportExcel { public static byte[] ExportToExcelFromDataTable(DataTable dt) { using (var workbook = new XLWorkbook()) { var worksheet = workbook.Worksheets.Add("Sheet1"); // 写入表头并设置样式 for (int col = 0; col < dt.Columns.Count; col++) { var cell = worksheet.Cell(1, col + 1); cell.Value = dt.Columns[col].ColumnName; // 表头样式:加粗、浅蓝色背景、居中对齐 cell.Style.Font.Bold = true; cell.Style.Fill.BackgroundColor = XLColor.LightBlue; cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; } // 为表头行设置筛选(仅需一次) worksheet.Row(1).SetAutoFilter(); // 写入数据并设置样式 for (int row = 0; row < dt.Rows.Count; row++) { int currentRow = row + 2; for (int col = 0; col < dt.Columns.Count; col++) { var cell = worksheet.Cell(currentRow, col + 1); var value = dt.Rows[row][col]; // 保留原始数据类型,避免转为字符串丢失格式 cell.Value = value == DBNull.Value ? null : value; // 交替行背景:奇数数据行(行号3、5...)设为浅灰,偶数行(行号2、4...)白色 if (currentRow % 2 != 0) { cell.Style.Fill.BackgroundColor = XLColor.LightGray; } else { cell.Style.Fill.BackgroundColor = XLColor.White; } // 设置单元格边框:所有边框细实线 cell.Style.Border.TopBorder = XLBorderStyleValues.Thin; cell.Style.Border.BottomBorder = XLBorderStyleValues.Thin; cell.Style.Border.LeftBorder = XLBorderStyleValues.Thin; cell.Style.Border.RightBorder = XLBorderStyleValues.Thin; } } // 自动调整列宽,包含表头和数据 worksheet.Columns().AdjustToContents(); using (var memoryStream = new MemoryStream()) { workbook.SaveAs(memoryStream); return memoryStream.ToArray(); } } } } }
控制器方法(无需修改)
public async Task<IActionResult> ExportBookingsToExcel(string dateRange, int orderStatus = -1) { // 解析日期范围 DateTime? FromDate = null; DateTime? ToDate = null; if (!string.IsNullOrEmpty(dateRange)) { var dates = dateRange.Split(" - "); if (dates.Length == 2) { if (DateTime.TryParseExact(dates[0], "MM/dd/yyyy", null, System.Globalization.DateTimeStyles.None, out var start)) FromDate = start; if (DateTime.TryParseExact(dates[1], "MM/dd/yyyy", null, System.Globalization.DateTimeStyles.None, out var end)) ToDate = end; } } var data = await _adminRepository.BookingsList(-1, -1, Convert.ToInt32(orderStatus), -1, FromDate, ToDate); DataTable dt = DataTableConverter.ToDataTable(data); // 将DataTable转换为Excel字节数组 byte[] fileBytes = ExportExcel.ExportToExcelFromDataTable(dt); string FileName = "BookingList" + "_" + dateRange + "_" + orderStatus + ".xlsx"; // 返回Excel文件 return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", FileName); }
关键修正点说明
- 筛选设置:移除每列单独设置筛选的代码,改为仅对表头行设置一次筛选,避免功能冲突
- 数据类型保留:不再强制将所有值转为字符串,直接赋值原始数据,保留日期、数字等原生格式
- 交替行逻辑:调整行号判断条件,使奇数数据行显示浅灰背景,匹配常见表格阅读习惯
- 边框添加:为每个单元格设置细实线边框,还原预期的表格规整样式
- 表头对齐:添加表头文字居中对齐,提升视觉可读性
内容的提问来源于stack exchange,提问作者PHioNiX
相关产品推荐
相关产品推荐

