C# 使用Epplus导出Excel [3]:合并列连续相同数据

心已入冬 提交于 2020-11-21 03:32:13

 

C# 使用Epplus导出Excel [1]:导出固定列数据

C# 使用Epplus导出Excel [2]:导出动态列数据

C# 使用Epplus导出Excel [3]:合并列连续相同数据

C# 使用Epplus导出Excel [4]:合并指定行

C# 使用Epplus导出Excel [5]:样式

 

导出的Excel数据,列连续相同的则合并并水平垂直居中

原始数据

合并后的数据

代码如下:

/// <summary>
        /// 合并列
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="startRowIndex"></param>
        /// <param name="items"></param>
        /// <param name="propertySelectors"></param>
        /// <param name="compareColIndex">比较的列</param>
        /// <param name="mergeColIndex">合并的列集合</param>
        public static void MergeColCells(ExcelWorksheet sheet, int startRowIndex, IList<Student> items, Func<Student, object>[] propertySelectors, int compareColIndex,List<int> mergeColIndexs)
        {
            Dictionary<int, int> dicMerge = new Dictionary<int, int>();
            var preData = string.Empty;
            int index = 0;
            for (var i = 0; i < items.Count; i++)
            {
                var currData = propertySelectors[compareColIndex](items[i]);
                if (string.IsNullOrEmpty(preData) || currData.ToString() != preData)
                {
                    preData = currData.ToString();
                    dicMerge.Add(i, i);
                    index = i;
                }
                else
                {
                    dicMerge[index] = i;
                }

                for (var j = 0; j < propertySelectors.Length; j++)
                {
                    var colData = propertySelectors[j](items[i]);
                    sheet.Cells[i + startRowIndex, j + 1].Value = colData;
                }
            }

            foreach (var item in dicMerge)
            {
                if (item.Value - item.Key > 0)
                {
                    for (int i = 0; i < mergeColIndexs.Count; i++)
                    {
                        sheet.Cells[item.Key + startRowIndex, mergeColIndexs[i] + 1, item.Value + startRowIndex, mergeColIndexs[i] + 1].Merge = true;
                        sheet.Cells[item.Key + startRowIndex, mergeColIndexs[i] + 1, item.Value + startRowIndex, mergeColIndexs[i] + 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        sheet.Cells[item.Key + startRowIndex, mergeColIndexs[i] + 1, item.Value + startRowIndex, mergeColIndexs[i] + 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    }
                }
            }
        }

 

List<int> mergeColIndexs = new List<int>();
                mergeColIndexs.Add(0);
                mergeColIndexs.Add(2);
                EpplusHelper.MergeColCells(worksheet,2,studentList,columnsValueList.ToArray(),0, mergeColIndexs);

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!