epplus动态合并列数据
private static void SetColMerge(DataTable tb, ExcelWorksheet worksheet, string dtColumnName)
{
KeyValuePair<bool, int> isMergeAndStartRowIndex = new KeyValuePair<bool, int>(false, 2);
bool isLast = false;
for (int i = 1; i <= tb.Rows.Count; i++)
{
for (int j = 1; j <= tb.Columns.Count; j++)
{
if (tb.Columns[j - 1].ColumnName == dtColumnName)
{
if (i != 1 && tb.Rows[i - 1][j - 1].ToString() != tb.Rows[i - 2][j - 1].ToString())
{
isMergeAndStartRowIndex = new KeyValuePair<bool, int>(true, isMergeAndStartRowIndex.Value);
}
if (i == tb.Rows.Count)
{
isLast = true;
isMergeAndStartRowIndex = new KeyValuePair<bool, int>(true, isMergeAndStartRowIndex.Value);
}
if (isMergeAndStartRowIndex.Key)
{
int startRowIndex = isMergeAndStartRowIndex.Value;
if (isLast)
{
//判断当前行和上一行是不是一样
if (tb.Rows[i - 1][j - 1].ToString() != tb.Rows[i - 2][j - 1].ToString())
{
worksheet.Cells[startRowIndex, j, i, j].Merge = true;
}
else
{
worksheet.Cells[startRowIndex, j, i + 1, j].Merge = true;
}
}
else
{
worksheet.Cells[startRowIndex, j, i, j].Merge = true;
isMergeAndStartRowIndex = new KeyValuePair<bool, int>(false, i + 1);
}
}
}
}
}
}