FireFrog69
FireFrog69

Reputation: 19

Getting a random cell from excel file using c#.net Interop framework consoleApp

Getting a random cell from excel file using c#.net framework consoleApp so I tried this but it gives me this exception:

System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800A03EC'

Workbook excelBook = excelApp.Workbooks.Open(@"C:\\Projects\\ExcelSingleValue\\kTest.xlsx");
_Worksheet excelSheet = excelBook.Sheets[1];
Range excelRange = excelSheet.UsedRange;

int rows = excelRange.Rows.Count;
int cols = excelRange.Columns.Count;

Random randomName = new Random(); 
Console.WriteLine((excelRange.Cells[randomName.Next(rows),1].Value2.ToString()));

Upvotes: 1

Views: 168

Answers (1)

Automate This
Automate This

Reputation: 31364

You are very close...

Note that randomName.Next(rows) can return zero. If it does then .Cells[randomName.Next(rows),1] will give you the error you see.

If your sheet has nothing on it then rows will always equal 1 and you have a 50% chance of the random number being zero.

Solution: Set the minimum value to 1 like this: Next(1, rows)

Console.WriteLine((excelRange.Cells[randomName.Next(1, rows),1].Value2.ToString()));

Upvotes: 1

Related Questions