0

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 ?

2 Answers 2

1

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very welcome, glad to help. If this (or any other response) answered your question, don't forget to mark it as such so others can know.
1

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

1 Comment

Could you post an example using my procedure here please !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.