为什么我在我的Console.WriteLine“,'{0}'”,String上不断获取System.IndexOutOfRangeException?声明?

问题描述

我正在使用Visual Studio中C#中的Web爬网程序,该爬网程序将Excel电子表格中的URL读取为字符串数组,稍后将通过这些字符串访问网站以从中抓取信息。我现在正在调试它,但是由于某种原因,每当我尝试将字符串打印到控制台时,都会出现超出范围的异常。

我正在使用IronXL Excel接口库在Excel电子表格中进行读写。而且,异常始终发生在“ Console.WriteLine(“,'{0}'”,String);“语句位于。

以下是涉及的类变量

    public static int NUMBER_OF_ENTRIES = 90;
    public static String [] URLs = new String [NUMBER_OF_ENTRIES];
    public static String PATH_OF_IO_DOC = "C:\\Users\\Owner\\Desktop\\List of Clubs.xlsx";
    public static String SHEET_NAME = "Sheet1";

这是所涉及方法代码

private void buttonGetURLs_Click(object sender,EventArgs e)
    {
        //read the URLs from the excel doc to an array of strings
        WorkBook wb = WorkBook.Load(PATH_OF_IO_DOC);
        WorkSheet ws = wb.GetWorkSheet(SHEET_NAME);

        int rowCount = NUMBER_OF_ENTRIES;
        //start at row 2 to skip the first header
        for (int i = 2; i < rowCount; i++)
        {
            //skip header lines
            if (!((rowCount == 13) || (rowCount == 16) || (rowCount == 31) || (rowCount == 32) || (rowCount == 33)))
            {
                //get value by cell address
                //string address_val = ws["A" + rowCount].ToString();
                //get value by row and column indexing
                string index_val = ws.Rows[rowCount].Columns[1].ToString();

                //read each cell's value to the array of URLs
                URLs[rowCount] = index_val;
                
                //check to make sure correct values are collected
                Console.WriteLine(",'{0}'",index_val);
            }
        }
    }

解决方法

这是错误的行,因为URL最多可以基于rowCount-1从0开始:

URLs[rowCount] = index_val;

您可能要使用i索引

URLs[i] = index_val;