C#使用Microsoft.Office.Interop.Excel读取Excel单元格值

Kur*_*ula 5 c# excel excel-interop

我正在尝试提取Excel单元格值。我能够成功提取行值。我应该怎么做才能将每​​个单元格值从行中拉出?

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();
Run Code Online (Sandbox Code Playgroud)

use*_*820 6

尝试这个:

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

我的测试文件的输出:

输入

输出

完整代码:

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);
Run Code Online (Sandbox Code Playgroud)

多行的编辑输入:

输入2

输出 2