I'm trying to read data from an Excel file to a DataTable
. I know that we can assign different DataTypes
for a DataColumn
when adding columns to a DataTable
. So far I have tried the following,
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2]
{
new Datacolumn("column1", typeof(string)),
new DataColumn("column2", typeof(int))
});
And my excel file has data in two columns as follows,
column1------column2
abc----------------230
def----------------230tr
As you can see above, the second row second column has a value of '230tr' which the DataTable
should not accept an throw an exception with the invalid data field and row number.
Praveena.
Thank you everyone for their response and I found an easy solution for my question while working with DataTables
. My main task was to read data rows from an Excel file sheet and validate each row data before adding it to my database table(using OracleBulkCopy) and notify the user with any invalid data fields in the Excel file sheet.
While I was importing data into the DataTable
from the Excel file sheet using oda.Fill(dt);
I realized that some of the DataRow
fields are empty(null) during the process of data addition to DataTable
.
As I have mentioned above in the main question we can assign the DataType
for a DataColumn
in a DataTable
as follows,
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3]
{
new Datacolumn("column1", typeof(string)),
new DataColumn("column2", typeof(double)),
new DataColumn("column3", typeof(DateTime))
});
And my Excel file sheet would be as follows,
column1-----------------column2----------------------column3
abcd----------------------20000-------------------------20-Dec-2018
efgh-----------------------56500.5----------------------xyz17-Mar-2018
ijklm-----------------------67000------------------------1-Jan-2018
In the above table 3rd row 3rd column RowData
is in invalid date type (xyz17-Mar-2018). While performing oda.Fill(dt); for the above table, this data field gets added as a null RowData
to the DataTable
. It would be the same for other columns if the importing data fields are not in the type of defined DataColumn
type. So My final step was to check each row data of DataTable
which has a null field and throw the user with an error message mentioning the row number and column name.
int errorRowNumber = 0;
private bool validateDataTableData(DataTable dt, string dtColumnName)
{
Boolean isTrue = false;
foreach (DataRow r in dt.Rows)
{
if(!string.IsNullOrEmpty(r[dtColumnName].ToString()))
{
isTrue = false;
errorRowNumber = dt.Rows.IndexOf(r) + 2;
break;
}
}
return isTrue;
}