-2
我想从Excel电子表格中获取单元格的值。该值存储在sheet1,单元格A2中,该列位于名为Item的列标题下。下面的代码总是将该值作为空值返回。请帮我拿到存储在A2中的值。如何从存储在内存中的Excel表中读取值c#
using Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class ExcelUtil
{
public static DataTable ExcelToDataTable(string fileName)
{
FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
DataTableCollection table = result.Tables;
DataTable resultTable = table["Sheet1"];
return resultTable;
}
public static List<Datacollection> dataCol = new List<Datacollection>();
public static void PopulateInCollection(string fileName)
{
DataTable table = ExcelToDataTable(fileName);
//Iterate through all the rows and columns of the Table
for (int row = 1; row <= table.Rows.Count; row++)
{
for (int col = 0; col < table.Columns.Count; col++)
{
Datacollection dtTable = new Datacollection()
{
rowNumber = row,
colName = table.Columns[col].ColumnName,
colValue = table.Rows[row - 1][col].ToString()
};
//Add all the details for each row
dataCol.Add(dtTable);
}
}
}
public static string ReadData(int rowNumber, string columnName)
{
try
{
//Retrieving Data using LINQ
string data = (from colData in dataCol
where colData.colName == columnName && colData.rowNumber == rowNumber
select colData.colValue).SingleOrDefault();
//var data = dataCol.Where(x => x.colName == columnName && x.rowNumber == rowNumber).SingleOrDefault().colValue;
return data.ToString();
}
catch (Exception e)
{
e.Message.ToString();
return null;
}
}
private static void mytest()
{
string itemNo = ExcelUtil.ReadData(1, "Item");
}
}
public class Datacollection
{
public int rowNumber { get; set; }
public string colName { get; set; }
public string colValue { get; set; }
}
}
哪种方法返回null?你有没有尝试调试代码,看看它为什么返回null?我应该如何在我的机器上运行此代码?我应该打电话给哪种方法? –
@ChetanRanpariya您需要在PC上本地保存一个excel工作表,并有几行,第一行将有标题,您可以将任何东西放入第二行。是的,我尝试过调试,但我得到了同样的错误。 :resultTable \t错误CS0103:名称'resultTable'在当前上下文中不存在。 – Tester
我忘了补充说我也有我的初始化类的文件名:ExcelUtil.PopulateInCollection(@“Data.xlsx”);应用程序无法获取itemno字段的字符串(这是Excel电子表格中的A2) – Tester