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

excelSheetscounterの配列にアクセスしiています。おそらくi 、プログラムの開始時に一度初期化0し、コード内でリセットしていません。そのため、例外が発生しています。array を定義しているコードで、その後、次のようexcelSheetsに設定iします。0

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 に答える