5

我正在使用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();
    }
4

2 回答 2

1

对于 .XLSX 文件,我使用 OpenXML SDK: http ://www.microsoft.com/en-us/download/details.aspx?id=30425

对于 XLS 文件,我使用 OleDbConnection,如下所示:

 OleDbConnection oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath+ ";Extended Properties='Excel 12.0;HDR=NO;IMEX=1;';");
            oledbConn.Open();
            OleDbCommand cmd = new OleDbCommand();
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            DataSet ds = new DataSet();

            DataTable dt = oledbConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
            string workSheetName = (string)dt.Rows[0]["TABLE_NAME"];

            cmd.Connection = oledbConn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * FROM [" + workSheetName + "]";

            oleda = new OleDbDataAdapter(cmd);

            oleda.Fill(ds, "Donnees");

            oledbConn.Close();
            return ds.Tables[0];
于 2014-02-18T10:11:01.137 回答
0
        DataTable DT = new DataTable(); 
        FileStream stream = File.Open(Filepath, FileMode.Open, FileAccess.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        DataSet result = excelReader.AsDataSet();
        excelReader.Close();
        DT = result.Tables[0];
于 2015-09-03T07:05:36.220 回答