0

这是我第一次选择它工作正常的文件。当我再次选择具有更新值的相同文件时,它给出:索引超出了数组错误的范围,知道出了什么问题,我该如何实现?我正在使用具有更新数据的相同 excel 文件。这是下面的代码:

  lblDisplay.Text = string.Empty;
   if (radSite.Checked==true)
            {
                if (openFileDialog.ShowDialog(this) == DialogResult.OK)
                {
                    path = openFileDialog.InitialDirectory + openFileDialog.FileName;
                }
                string constring = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + path + "; Extended Properties=Excel 12.0 Xml";
                OleDbConnection con = new OleDbConnection(constring);
                try
                {
                    con.Open();
                    dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    String[] excelSheets = new String[dt.Rows.Count];
                    foreach (DataRow row in dt.Rows)
                    {
                        excelSheets[i] = row["TABLE_NAME"].ToString(); //am getting error at this point
                        i++;
                    }

                    for (int j = 0; j < excelSheets.Length; j++)
                    {
                        string query = "SELECT * FROM [" + excelSheets[j] + "]; ";
                        OleDbDataAdapter adp = new OleDbDataAdapter(query, constring);

                        DataSet ds = new DataSet();
                        string sCode = string.Empty;
                        string sdescription = string.Empty;
                        adp.Fill(ds);

                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            sCode = Convert.ToString(dr[1]);
                            sdescription = Convert.ToString(dr[2]);
                            // if (!(string.IsNullOrEmpty(hCode) && string.IsNullOrEmpty(description)))
                            {

                                dboject.InsertSiteNameIntoDatabase(sCode, sdescription);

                            }
                        }


                    }
                    lblDisplay.Text = "Inserted successfully";
                }
                catch (Exception ex)
                {
                    dboject.VMSLog(ex.Message);

                }
                finally
                {
                    con.Close();

                }

            }
4

1 回答 1

1

excelSheets您正在访问counter 上的数组i,您可能i 在程序开始时进行了一次初始化,然后您没有将其重置回0代码中。这就是为什么你得到例外。在您定义数组的代码中excelSheets,之后设置i0

String[] excelSheets = new String[dt.Rows.Count];
i = 0; //here
//then rest of your code
foreach (DataRow row in dt.Rows)
{
    excelSheets[i] = row["TABLE_NAME"].ToString(); 
    i++;
}
于 2013-04-17T06:16:26.630 回答