使用Excel打印功能时为WPF DataGrid表头添加下划线
解决WPF DataGrid导出Excel表头下划线问题
问题分析
你当前代码里的下划线设置是给所有单元格统一添加,且放在数据行循环里重复执行,没有单独针对表头行(第1行)做样式设置,同时还误用了属性——应该用Font.Underline而非Font.FontStyle来设置下划线,这就是表头下划线不生效的核心原因。
修改方案
下面是调整后的完整代码,重点优化了表头样式设置逻辑,并补充了Excel资源释放逻辑避免进程残留:
private void OnDataGridPrinting(object sender, RoutedEventArgs e) { System.Windows.Controls.PrintDialog Printdlg = new System.Windows.Controls.PrintDialog(); if ((bool)Printdlg.ShowDialog().GetValueOrDefault()) { // 创建Excel应用实例 Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); // 创建新工作簿 Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); Microsoft.Office.Interop.Excel._Worksheet worksheet = null; app.Visible = false; // 获取并激活第一个工作表 worksheet = workbook.Sheets["Sheet1"]; worksheet = workbook.ActiveSheet; worksheet.Name = SelectedCustomer.CustName; CollectionViewSource itemCollectionViewSources; itemCollectionViewSources = (CollectionViewSource)(FindResource("ItemCollectionViewSources")); // 写入DataGrid表头到Excel第1行 for (int i = 1; i < dgEndOfYear.Columns.Count + 1; i++) { worksheet.Cells[1, i] = dgEndOfYear.Columns[i - 1].Header; } // 单独设置表头样式:下划线+居中对齐 var headerRange = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, dgEndOfYear.Columns.Count]]; headerRange.Font.Underline = Microsoft.Office.Interop.Excel.XlUnderlineStyle.xlUnderlineStyleSingle; headerRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; // 设置全局列宽和数据单元格对齐方式(移到循环外,仅执行一次) worksheet.Columns.ColumnWidth = 14; worksheet.Cells.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; // 写入DataGrid数据行到Excel for (int i = 0; i < CustomerEOYTotals.Count; i++) { absvwEndOfYearTotal1 line = CustomerEOYTotals[i]; worksheet.PageSetup.CenterHeader = "&UEnd Of Year Report " + CurrentYear; worksheet.Cells[i + 2, 1] = line.CalendarYear; worksheet.Cells[i + 2, 2] = line.CustName; worksheet.Cells[i + 2, 3] = line.MonthName; worksheet.Cells[i + 2, 4] = line.SumGal.Value.ToString(); worksheet.Cells[i + 2, 5] = line.Manifest; } // 打印工作簿 workbook.PrintOut(); // 释放Excel资源,避免后台进程残留 workbook.Close(false); app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); } }
关键改动说明
- 用
Range选中整个表头行,单独对其设置下划线样式,纠正了之前的属性误用 - 将列宽、全局对齐等重复操作移到数据循环外,提升代码执行效率
- 添加Excel资源释放逻辑,防止打印完成后后台残留Excel进程
内容的提问来源于stack exchange,提问作者Mr.E
相关产品推荐
相关产品推荐

