【发布时间】:2020-10-29 19:51:36
【问题描述】:
我正在 Visual Studio 中使用 C# 编写一个网络爬虫,该爬虫将 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);
}
}
}
【问题讨论】:
-
还有错误的堆栈跟踪?
-
您确定错误在写行中吗?查看您的代码,我认为您使用的是 rowCount 变量而不是 i...您执行了一个循环,但在循环内您使用的是 rowCount 变量而不是 i。并且,如果 NUMBER_OF_ENTRIES 是 URLs 数组的大小,Console.WriteLine 之前的行将因 IndexOutOfRangeException 而失败,因为如果数组的大小是 100,则最后一个元素是 99
-
请查看minimal reproducible example 发布代码指南和edit 问题。
Console.WriteLine(", '{0}'", index_val);不太可能产生该错误(Console.WriteLine(", '{1}'", index_val);会失败,但类型相似但类型不同 -FormatException)
标签: c# excel string indexoutofrangeexception console.writeline