-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