【发布时间】:2020-08-03 06:25:58
【问题描述】:
使用过 ExcelDataReader NuGET 包。
这是设置它的类 -
private static DataTable ExcelToDataTable(string fileName)
{
//open file and returns as Stream
FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
//Createopenxmlreader via ExcelReaderFactory
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx
//Set the First Row as Column Name
excelReader.IsFirstRowAsColumnNames = true;
//Return as DataSet
DataSet result = excelReader.AsDataSet();
//Get all the Tables
DataTableCollection table = result.Tables;
//Store it in DataTable
DataTable resultTable = table["Sheet1"];
//return
return resultTable;
}
static List<Datacollection> dataCol = new List<Datacollection>();
public static void PopulateInCollection(string fileName)
{
DataTable table = ExcelToDataTable(fileName);
//Iterate through 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
{
//Retriving Data using LINQ to reduce much of iterations
string data = (from colData in dataCol
where colData.colName == columnName && colData.rowNumber == rowNumber
select colData.colValue).SingleOrDefault();
//var datas = dataCol.Where(x => x.colName == columnName && x.rowNumber == rowNumber).SingleOrDefault().colValue;
return data.ToString();
}
catch (Exception)
{
return null;
}
}
}
public class Datacollection
{
public int rowNumber { get; set; }
public string colName { get; set; }
public string colValue { get; set; }
}
}
它在代码中调用 -
//setting the excel file location
ExcelLib.PopulateInCollection(@"C:\Users\User1\Documents\data.xlsx");
//reading data from row 1 & column named middlename
xrmApp.Entity.SetValue("middlename", ExcelLib.ReadData(1, "middlename"));
我希望能够以不同的方法使用此代码,并且对于每种方法我需要不同的数据。 他们也是如此,我可以在代码中添加一个工作表编号参数,这样我就可以在读取行号和列号时指定要查看的工作表。
谢谢!
【问题讨论】:
-
为了更好地解决您的问题,我需要与您确认一件事。你的最终目标是什么?主题是您要读取数据,但在代码 Entity.SetValue 中您正在设置值。因此,我很困惑。如果你想从同一个excel文件中的多张表中读取数据,我建议你可以将你当前的excel转换为数据集,那么我们只需要读取数据集中的数据表即可。只要你能实现datatable中的数据,我们就可以实现exel文件中的任何数据。
-
@JackJJun-MSFT.. 我将从 excel 中读取一个包含一个单词的单元格值,然后在我的代码中使用“ ExcelLib.ReadData(1, "middlename") 设置该单词" .. 所以这是从 excel 表中读取第 1 行和列名以从该单元格中获取单词。现在我只能从一个工作表中读取,所以我想要的是有另一个参数,我可以设置工作表编号以及行和列名。我希望这能解决问题,谢谢
标签: c# visual-studio selenium nuget-package exceldatareader