Reading data from Excel file [closed]
I am creating windows application to insert data from Excel file into database. My application is working properly but after displaying data from excel file into data grid view and inserting into database, it inserts a blank row.
Here is my code,
//we need to copy the data from datagridview into data table
DataTable dtable = new DataTable();
dtable.TableName = "PRODUCTS";
//we need to copy column from datagridview into data table
foreach (DataGridViewColumn col in ExcelDataGV.Columns)
{
dtable.Columns.Add(col.DataPropertyName, col.ValueType);
}
//we need 开发者_StackOverflow中文版to copy rows from datagridview into data table
foreach (DataGridViewRow row in ExcelDataGV.Rows)
{
if (row.IsNewRow)
continue;
DataRow dtRow = dtable.NewRow();
for (int i = 0; i < ExcelDataGV.Columns.Count; i++)
dtRow[i] = (row.Cells[i].Value == null ? DBNull.Value : row.Cells[i].Value);
dtable.Rows.Add(dtRow);
}
//foreach loop will read data from data table and insert/add those value in database
foreach (DataRow dr in dtable.Rows)
{
}
Do I need to modify my for loop statement?
I don't know if this is your problem since you're not showing the code to insert data into the table, but sometimes Excel add an empty row after the last populated row.
It may also happen that you have some invisible content in that row.
If this is the issue you should simply ignore the last row.
Better yet is to know the amount of rows to read from the excel file.
精彩评论