如何为导出至Excel的DataTable添加指定格式表头?
如何为导出Excel的DataTable添加指定格式的表头
我需要给导出到Excel的DataTable添加指定格式的表头,但目前无法实现:
- 期望格式:顶部显示企业名称和PAN号,下方是分组合并的两行表头(比如“日期信息”合并对应列,下方是Date、Miti;“发票信息”对应Invoice No;“买方信息”对应Buyer Name、Buyer Pan等,所有表头单元格居中加粗)
- 当前导出结果:仅显示DataTable列名组成的单行普通表头,无合并和分组样式
以下是我的实现代码:
public void btn_excel_Click(object sender, EventArgs e) { DataTable dt_m = blu.checkbusiness(); if (dt_m.Rows.Count > 0) { Business_Name = dt_m.Rows[0]["business_name"].ToString(); if (Business_Name.Length >= 30) { Business_Name = Business_Name.Substring(0, 30); } pan_no = dt_m.Rows[0]["pan_no"].ToString(); } dt.Columns.Add("Date"); dt.Columns.Add("Miti"); dt.Columns.Add("Invoice No", typeof(decimal)); dt.Columns.Add("Buyer Name"); dt.Columns.Add("Buyer Pan"); dt.Columns.Add("ItemName"); dt.Columns.Add("Quantity", typeof(decimal)); dt.Columns.Add("Unit"); dt.Columns.Add("Total Sales", typeof(decimal)); dt.Columns.Add("Discount", typeof(decimal)); dt.Columns.Add("Taxable Amount", typeof(decimal)); dt.Columns.Add("VAT", typeof(decimal)); dt.Columns.Add("Export Sales", typeof(decimal)); dt.Columns.Add("Country"); dt.Columns.Add("PragyapanPatraNo"); dt.Columns.Add("PragyapanPatraMiti"); for (int i = 0; i < dt_report.Rows.Count; i++) { dt.Rows.Add(); DateTime date = Convert.ToDateTime(dt_report.Rows[i]["date_of_sale"].ToString()); datenepali = dc.dateConvertToNepali(date); dt.Rows[i]["Miti"] = datenepali; dt.Rows[i]["Date"] = date.ToShortDateString(); dt.Rows[i]["Buyer Name"] = dt_report.Rows[i]["customer_name"]; dt.Rows[i]["Buyer Pan"] = dt_report.Rows[i]["customer_no"]; dt.Rows[i]["ItemName"] = dt_report.Rows[i]["item_name"]; dt.Rows[i]["Quantity"] = dt_report.Rows[i]["quantity"]; dt.Rows[i]["Unit"] = "Pieces"; // 注:原代码此处省略了剩余列的赋值逻辑 } // 原导出逻辑 string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\POS\\IRDSalesReportFormat Excel\\"; if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt, "Ird Sales Format"); wb.SaveAs(folderPath + DateTime.Now.ToString("yyyy-MM-dd ss") + "IRDSalesReportFormat.xlsx"); MessageBox.Show("Your sales excel report has been export to document", "IRD Sales Report Fomat Export", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
解决方案(基于ClosedXML实现)
直接添加DataTable会自动生成单行表头,要实现自定义格式表头,需要手动构建表头区域,再写入数据:
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\POS\\IRDSalesReportFormat Excel\\"; if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } using (XLWorkbook wb = new XLWorkbook()) { // 创建工作表 IXLWorksheet ws = wb.Worksheets.Add("Ird Sales Format"); // 1. 添加顶部企业信息(合并第一行全列) ws.Cell(1, 1).Value = $"企业名称:{Business_Name} | PAN号:{pan_no}"; ws.Range(1, 1, 1, dt.Columns.Count).Merge(); ws.Range(1, 1, 1, dt.Columns.Count).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; ws.Range(1, 1, 1, dt.Columns.Count).Style.Font.Bold = true; // 2. 构建分组表头(第二行是分组标题,第三行是列名) // 定义分组与对应列索引(列从1开始) var headerGroups = new List<(string GroupName, int StartCol, int EndCol)> { ("日期信息", 1, 2), ("发票信息", 3, 3), ("买方信息", 4, 5), ("商品信息", 6, 8), ("金额信息", 9, 12), ("出口信息", 13, 14), ("许可证信息", 15, 16) }; // 设置第二行分组表头 foreach (var group in headerGroups) { ws.Cell(2, group.StartCol).Value = group.GroupName; ws.Range(2, group.StartCol, 2, group.EndCol).Merge(); ws.Range(2, group.StartCol, 2, group.EndCol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; ws.Range(2, group.StartCol, 2, group.EndCol).Style.Font.Bold = true; ws.Range(2, group.StartCol, 2, group.EndCol).Style.Fill.BackgroundColor = XLColor.LightGray; } // 设置第三行列名表头 for (int col = 0; col < dt.Columns.Count; col++) { ws.Cell(3, col + 1).Value = dt.Columns[col].ColumnName; ws.Cell(3, col + 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; ws.Cell(3, col + 1).Style.Font.Bold = true; ws.Cell(3, col + 1).Style.Fill.BackgroundColor = XLColor.LightGray; } // 3. 写入DataTable数据(从第4行开始) ws.Cell(4, 1).InsertData(dt.AsEnumerable()); // 自动调整列宽 ws.Columns().AdjustToContents(); // 保存文件 string fileName = folderPath + DateTime.Now.ToString("yyyy-MM-dd ss") + "IRDSalesReportFormat.xlsx"; wb.SaveAs(fileName); MessageBox.Show("销售报表已导出至文档文件夹", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information); }
关键说明
- 先创建空白工作表,手动构建顶部信息、分组表头,再插入DataTable数据
- 使用
Merge()方法实现单元格合并,通过Style设置字体、对齐、背景色等样式 - 数据从第4行开始插入,避免覆盖自定义表头区域
内容的提问来源于stack exchange,提问作者Aman Mahaseth
相关产品推荐
相关产品推荐

