C# reading Excel cell values using Microsoft.Office.Interop.Excel

Kurkula picture Kurkula · Nov 1, 2016 · Viewed 11.4k times · Source

I am trying to pull Excel cell values. I am able to pull a row value successfully. What should I do to pull each cell value out of the row?

using Microsoft.Office.Interop.Excel;

string pathToExcelFile = @"C:\Users\MyName\Desktop\Log.xls";

Application xlApp = new Application();
Workbook xlWorkbook = xlApp.Workbooks.Open(pathToExcelFile, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

_Worksheet xlWorksheet = (_Worksheet)xlWorkbook.Sheets[1];
Range xlRange = xlWorksheet.UsedRange;

var rowValue = ((Range)xlRange.Cells[2, 1]).Value2.ToString();

Answer

user1274820 picture user1274820 · Nov 1, 2016

Try this:

foreach (Range c in xlRange.Cells)
{
    Console.WriteLine("Address: " + c.Address + " - Value: " + c.Value);
}

Output from my test file:

Input

Output

Complete code:

string testingExcel = @"C:\TestingExcel.xlsx";
Application xlApp = new Application();
Workbook xlWorkbook = xlApp.Workbooks.Open(testingExcel, Type.Missing, true);
_Worksheet xlWorksheet = (_Worksheet)xlWorkbook.Sheets[1];
Range xlRange = xlWorksheet.UsedRange;
foreach (Range c in xlRange.Rows.Cells)
{
    Console.WriteLine("Address: " + c.Address + " - Value: " + c.Value);
}
xlWorkbook.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);

Edited Input with multiple rows:

Input2

Output2