Hello @cenk
Your ImportToDataTable method return wrong Column name in Datatable. EX: 1,2,3,4,5,
and PID, ProductName and other column is consider as Row data. Which is wrong and create the issue while ColumnMappings.
Replace your Utility class to
public class Utility
{
public static DataTable ImportToDataTable(string filePath, string sheetName, bool hasHeader = true)
{
var dt = new DataTable();
var fi = new FileInfo(filePath);
// Check if the file exists
if (!fi.Exists)
throw new Exception("File " + filePath + " Does Not Exists");
// If you use EPPlus in a noncommercial context
// according to the Polyform Noncommercial license:
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using var xlPackage = new ExcelPackage(fi);
// get the first worksheet in the workbook
var worksheet = xlPackage.Workbook.Worksheets[sheetName];
// create all the needed DataColumn
foreach (var firstRowCell in worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
{
if (firstRowCell.Text == "ReferenceNo")
{
dt.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column), typeof(Guid));
}
else
{
dt.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
}
var startRow = hasHeader ? 2 : 1;
// place all the data into DataTable
for (int rowNum = startRow; rowNum <= worksheet.Dimension.End.Row; rowNum++)
{
var wsRow = worksheet.Cells[rowNum, 1, rowNum, worksheet.Dimension.End.Column];
DataRow row = dt.Rows.Add();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
}
return dt;
}
It will give you the correct column name in Datatable.
Hope this helps
If it does, please accept the answer.
Thanks
Naimish Makwana