我正在使用Excel 数据阅读器将一些数据读入实体框架数据库
下面的代码正在运行,但我需要进一步改进
首先 IsFirstRowAsColumnNames 似乎没有按预期工作,我必须改用 .Read 。
我最初用来选择特定工作表的软糖计划失败了,任何人都可以帮助这个 excelReader.Name 目前是没有意义的,除非我可以专门循环或选择一个工作表,我最初使用 .Read 来实现因此冲突。
参考实际的列标题名称来检索数据也很好,而不是索引,例如 SQL 客户端中的 var name = reader["applicationname"].ToString();
如果我无法实现上述目标,是否有更好的扩展可以用来读取 excel 数据。
public static void DataLoadAliases(WsiContext context)
{
const string filePath = @"Alias Master.xlsx";
var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
var excelReader = filePath.Contains(".xlsx")
? ExcelReaderFactory.CreateOpenXmlReader(stream)
: ExcelReaderFactory.CreateBinaryReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
excelReader.Read(); //skip first row
while (excelReader.Read())
{
if (excelReader.Name == "Alias Master")
{
var aliasId = excelReader.GetInt16(0);
var aliasName = excelReader.GetString(1);
//Prevent blank lines coming in from excel;
if (String.IsNullOrEmpty(aliasName)) continue;
context.Aliases.Add(new ApplicationAlias
{
AliasId = aliasId,
Name = aliasName,
});
}
else
{
excelReader.NextResult();
}
}
excelReader.Close();
context.SaveChanges();
}