C# 使用Epplus导出Excel [1]:导出固定列数据
C# 使用Epplus导出Excel [2]:导出动态列数据
C# 使用Epplus导出Excel [3]:合并列连续相同数据
导出的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);
来源:oschina
链接:https://my.oschina.net/u/4320155/blog/3657771