想要导出这样的表格
数据准备格式
附上源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util; using System.Data; using System.Text.RegularExpressions; namespace TestConsoleApp { /// <summary> /// 导出Excel /// </summary> public static class ExportHelper { public static void Export() { var dt = CreteTable(); var titles = GetExcelTitles(dt.Columns, out int maxTitleLevel); HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet( "Sheet1" ); var allRowCount = dt.Rows.Count + maxTitleLevel; //创建所有单元格 for ( int i = 0; i 0) { sheet.AddMergedRegion( new CellRangeAddress(tit.StartRow, tit.StartRow + tit.MergeRowCount, tit.StartColumn, tit.StartColumn + tit.MergeColumnCount)); } } //生成数据行 for ( int i = 0; i GetExcelTitles(DataColumnCollection columns, out int maxTitleLevel) { maxTitleLevel = 0; List levelExcelTitles = new List(); for ( var index = 0; index new { b.LevelCode, b.Title }) .Select(b => new ExcelTitle() { Title = b.Key.Title, StartRow = b.Min(c => c.RowIndex), MergeRowCount = b.Min(c => c.RowIndex) + 1 == b.Max(c => c.TotalLevel) ? titleLevel - b.Max(c => c.TotalLevel) : 0, StartColumn = b.Min(c => c.ColumnIndex), MergeColumnCount = b.Count() - 1, //排除自身 }).ToList(); return excelTitles; } } public class ExcelTitle { /// <summary> /// 标题 /// </summary> public string Title { get ; set ; } /// <summary> /// 开始行 /// </summary> public int StartRow { get ; set ; } /// <summary> /// 合并行 /// </summary> public int MergeRowCount { get ; set ; } /// <summary> /// 开始列 /// </summary> public int StartColumn { get ; set ; } /// <summary> /// 合并列 /// </summary> public int MergeColumnCount { get ; set ; } } public class LevelExcelTitle { /// <summary> /// 标题 /// </summary> public string Title { get ; set ; } public string LevelCode { get ; set ; } /// <summary> /// 第几行 /// </summary> public int RowIndex { get ; set ; } /// <summary> /// 第几列 /// </summary> public int ColumnIndex { get ; set ; } /// <summary> /// 总层 /// </summary> public int TotalLevel { get ; set ; } } } |
到此这篇关于.Net Core NPOI 导出多级表头的文章就介绍到这了,更多相关.Net Core NPOI 导出多级表头内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!