Reputation: 2057
I'm just using a simple code to write a list of string to excel as following
Excel.Application excelApp = new Excel.Application();
string myPath = Environment.CurrentDirectory + path + "\\reselts.xlsx";
excelApp.Workbooks.Open(myPath);
List <string> allterms = new List<string>(alltext.Split(' '));
allterms= allterms.Distinct().ToList();
allterms.RemoveAll(String.IsNullOrEmpty);
for (int i = 1; i < allterms.Count + 1; i++ )
{
excelApp.Cells[i, 1] = allterms[i];
}
excelApp.Visible = true;
But I got an error "index was out of range" ! what is wrong with my procedure ? can any help please ?
Upvotes: 0
Views: 1389
Reputation: 11832
In excel all indexes are 1-based. In C# all indexes are 0-based. In your code looks like you use 1-based access model for both: for excel and list.
Also, to increase the speed of inserting, it will be better to set values for range instead of for each cell. You can take a look on example I have here: http://outcoldman.com/en/blog/show/201
Upvotes: 1
Reputation: 5866
allterms.Count
is the total number of items in the List
. Your loop is trying to access Count + 1
, which doesn't exist.
For example, say there are 10 items in allterms
. The total count is equal to 10
and the index ranges from 0 - 9
, which is 10 items. What you're doing in your for loop is accessing items at the index range 1 - 10
, which is skipping the item at index 0
and attempting to access the item at index 10
, which doesn't exist.
Try this:
for (int i = 0; i < allterms.Count; i++ )
{
excelApp.Cells[i + 1, 1] = allterms[i];
}
Upvotes: 1