I've put in the following method that returns a value from an XLS file cell :
public static string ReadFromExcel(string filePath, int sheetNum, int xCell, int yCell)
{
List<string> rowValue = new List<string> {};
var ExcelFilePath = @filePath;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(ExcelFilePath);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[sheetNum];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
xlApp.ThisWorkbook.Close(); //<-- here it throws the exception in the title
xlApp.Quit();
return xlRange.Cells[xCell, yCell].Value2.ToString();
}
The current code obviously generates an exception because the I close the Workbook and app and then return the value. What's the way to add
xlApp.ThisWorkbook.Close();
xlApp.Quit();
and still return the value ?
Thanks.
Use a variable "returnValue", eg:
Update
The error code indicates one of these is the cause:
Perhaps your xCell, yCell's aren't in the UsedRange. Can you step through the code "Debug it" and post a screenshot that matches the scenario you're encountering? Thanks.
Solution
What you're encountering is explained here: How do I properly clean up Excel interop objects?
To over come it you can use AutoReleaseComObject or the original VSTO-Contrib. Here is some code to show you how to use it:
Here is the AutoReleaseComObject class:
Here is a screenshot showing you I got it working!!