I am trying to get the Columns data form an Excel file in lists by this way :
private void Form1_Load(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/test.xlsx");
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
List<string> FirstColumnValues = new List<string>();
List<string> SecondColumnValues = new List<string>();
for (int row=1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
switch (col)
{
case 1:
FirstColumnValues.Add(xlRange.Cells[row, col].Value2.ToString());
break;
case 2:
SecondColumnValues.Add(xlRange.Cells[row, col].Value2.ToString());
break;
}
}
}
if (FirstColumnValues.Count != 0 && SecondColumnValues.Count != 0)
{
xlWorkbook.Close();
xlApp.Quit();
MessageBox.Show("Completed");
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
}
The problem is, that the process EXCEL.EXE
is not closing even I have tried all the things to close it properly. I know there are many questions posted here about closing excel process properly. But I am not a professional and I have tried almost everything what I can do.
Still no luck.
So, Can anybody please tell me what is wrong with this code? And how the process can be closed once when all the data is stored in the lists?