【发布时间】:2015-09-03 15:05:36
【问题描述】:
我正在使用Excel Data Reader 将一些数据读入实体框架数据库
下面的代码正在运行,但我需要进一步改进
首先,IsFirstRowAsColumnNames 似乎没有按预期工作,我必须改用 .Read。
我最初用于选择特定工作表的软糖计划被破坏了,任何人都可以帮助这个 excelReader.Name 目前是没有意义的,除非我可以专门循环或选择我最初使用的工作表。阅读从而实现冲突。
参考实际的列标题名称来检索数据也很好,而不是索引,例如 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();
}
【问题讨论】:
-
附言。我一直在尝试使用 DataSet,但不确定如何使用这些对我有利。
标签: c# excel exceldatareader