I want to merge rows in my exported excel using epplus. This code below only works if I just have one same value in one column.
e.g (I merge same value in Col1 row) :
But, if I have another table like this, the code getting error while do merge (I merge same value in Col1 and Col2 row)
Pls, help me fix the code.
void mergeCells(DataTable dt, int startIndex, int totalColumns, ExcelWorksheet ws)
{
if (totalColumns == 0) return;
int i, count = 1;
ArrayList lst = new ArrayList();
lst.Add(ws.Cells[2, 1]);
var ctrl = ws.Cells[startIndex + 1, 1];
for (i = 1; i <= dt.Rows.Count; i++)
{
ExcelRange nextMerge = ws.Cells[i + totalColumns + 1, 1];
if (ctrl.Text == nextMerge.Text)
{
count++;
lst.Add(ws.Cells[i, 1]);
}
else
{
if (count > 1)
{
ws.Cells[i + 1, 1, i + count, 1].Merge = true;
mergeCells(new DataTable(lst.ToString()), startIndex + count, totalColumns, ws);
}
count = 1;
lst.Clear();
ctrl = ws.Cells[i + 2, startIndex];
lst.Add(ws.Cells[i, 1]);
}
}
if (count > 1)
{
ws.Cells[startIndex + 1, 1, startIndex + count, 1].Merge = true;
mergeCells(new DataTable(lst.ToString()), startIndex + count, totalColumns - 1, ws);
}
count = 1;
lst.Clear();
}
I have done like this:
public void WriteDataToSheet(DataTable data)
{
using (ExcelPackage excel = new ExcelPackage())
{
ExcelWorksheet ws = excel.Workbook.Worksheets.Add("Test");
ws.Cells["A1"].LoadFromDataTable(data, true);
ws.Cells[ws.Dimension.Address].AutoFitColumns();
var listObject = data.AsEnumerable()
.Select(x => new
{
Col1 = x.Field<string>("Col1"),
Col2 = x.Field<string>("Col2"),
Col3 = x.Field<string>("Col3")
}).ToList();
var lisa = listObject.GroupBy(x => x.Col1).
Select(x => new
{
Id = x.Key,
Quantity = x.Count(),
secondGroup = x.GroupBy(y => y.Col2)
.Select(y => new
{
ID = y.Key,
secondGroup = y.Count()
})
});
int A = 1, B = 0, C = 1, D = 0;
foreach (var item in lisa)
{
B = A + 1;
A += item.Quantity;
ws.Cells["A" + B + ":A" + A + ""].Merge = true;
ws.Cells["B" + B + ":B" + A + ""].Merge = true;
foreach (var item2 in item.secondGroup)
{
D = C + 1;
C += item2.secondGroup;
ws.Cells["C" + D + ":C" + C + ""].Merge = true;
}
}
// Save merged and modified file to the location
}
}