I have an Excel data which looks like below. Using ClosedXML, I've read the data into DataTable. Now again I need to store records into separate DataTable based on CID value. i.e., Records which are having same CID value should be stored into separate DataTable. And all those DataTable needs to be added to a list of DataTable.
Name | CID | ComapanyName | CCode | Address | Remarks |
---|---|---|---|---|---|
Anto | 12 | ABC Corp Cmp | ABCCo | AvenueSt | |
Anuj | 13 | XYZ Corp Cmp | XYZCo | AvenueSt | Fail |
Kathy | 12 | ABC Corp Cmp | ABCCo | AvenueSt | Fail |
Frank | 12 | ABC Corp Cmp | ABCCo | AvenueSt | Fail |
Henry | 13 | XYZ Corp Cmp | XYZCo | AvenueSt | Fail |
Chris | 14 | CTF Corp Cmp | CTFCo | AvenueSt | Fail |
After logic it should look like below.
Table 1:
Name | CID | ComapanyName | CCode | Address | Remarks |
---|---|---|---|---|---|
Anto | 12 | ABC Corp Cmp | ABCCo | AvenueSt | |
Kathy | 12 | ABC Corp Cmp | ABCCo | AvenueSt | Fail |
Frank | 12 | ABC Corp Cmp | ABCCo | AvenueSt | Fail |
Table 2:
Name | CID | ComapanyName | CCode | Address | Remarks |
---|---|---|---|---|---|
Anuj | 13 | XYZ Corp Cmp | XYZCo | AvenueSt | Fail |
Table 3:
Name | CID | ComapanyName | CCode | Address | Remarks |
---|---|---|---|---|---|
Chris | 14 | CTF Corp Cmp | CTFCo | AvenueSt | Fail |
ClosedXML code to read Excel data into DataTable:
private static System.Data.DataTable ReadExcelData(string filePath)
{
try
{
System.Data.DataTable dataTable = new System.Data.DataTable();
using (Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (XLWorkbook workBook = new XLWorkbook(stream))
{
var workSheet = workBook.Worksheet(1);
dataTable.TableName = workSheet.Name;
int lastRowIndex = workSheet.LastRowUsed().RowNumber();
int lastColumnIndex = workSheet.LastColumnUsed().ColumnNumber();
bool header = false;
foreach (IXLRow row in workSheet.Rows(1, lastRowIndex))
{
if (!header)
{
foreach (IXLCell cell in row.Cells(1, lastColumnIndex))
{
dataTable.Columns.Add(cell.GetFormattedString());
}
header = true;
}
dataTable.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells(1, lastColumnIndex))
{
dataTable.Rows[dataTable.Rows.Count - 1][i] = cell.GetFormattedString();
i++;
}
}
dataTable.Rows.RemoveAt(0);
}
}
return dataTable;
}
catch (Exception ex)
{
return null;
}
}