[英]C# reading Excel cell values using Microsoft.Office.Interop.Excel
I am trying to pull Excel cell values. 我想拉取Excel单元格值。 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();
Try this: 尝试这个:
foreach (Range c in xlRange.Cells)
{
Console.WriteLine("Address: " + c.Address + " - Value: " + c.Value);
}
Output from my test file: 我的测试文件输出:
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: 已编辑的多行输入:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.