开发者

Reading data from Excel file [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜