C#ExcelDataReader仅从特定列读取

时间:2019-03-15 15:14:03

标签: c# excel desktop-application exceldatareader

我正试图从我的Excel工作表中获取数据以将其添加到数据库中,该数据库运行良好,但我只希望数据位于特定标题下。 这是我的配置代码:

var headers = new List<string>;
DataSet result = excelDataReader.AsDataSet(new ExcelDataSetConfiguration()
        {
            ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
            {
                UseHeaderRow = true,
                ReadHeaderRow = rowReader =>
                {
                    for (var i = 0; i < rowReader.FieldCount; i++)
                        headers.Add(Convert.ToString(rowReader.GetValue(i)));
                },
                FilterColumn = (columnReader, columnIndex) =>
                    headers.IndexOf("LOCATION") == columnIndex
                    || headers.IndexOf("PARENT") == columnIndex
                    || headers.IndexOf("DESCRIPTION") == columnIndex
            }
        });

LOCATIONPARENTDESCRIPTION是列标题名称。 这是我用来将数据添加到数据库中的代码

foreach (DataTable table in result.Tables)
        {
            foreach (DataRow row in table.Rows)
            {

                if (!existedLocations.Any(l => l.ShortCode?.Replace(" ", String.Empty) == row[0].ToString().Replace(" ", String.Empty)))
                {
                    addtable.Name = addtable.NameAr = row[2].ToString().Substring(row[2].ToString().LastIndexOf(',') + 1);
                    addtable.ParentLocation = connection.Locations.FirstOrDefault(l => l.ShortCode == row[1].ToString()).Id;
                    addtable.LocationType = (int)LocationsTypes.Area;
                    addtable.ShortCode = row[0].ToString();
                    addtable.Category = (int)LocationsCategory.indoor;
                    addtable.IsActive = 1;
                    addtable.Isdeleted = 0;
                    existedLocations.Add(addtable);
                    connection.Locations.InsertOnSubmit(addtable);
                    connection.SubmitChanges();
                    addtable = new Location();
                }
            }
        }

工作表标题定义如下 sheet1 enter image description here

sheet2 enter image description here

1 个答案:

答案 0 :(得分:1)

好,您有两张纸,它们的标题相同,但位置不同。您的代码将第一张表的标题添加到列表中,然后将第二张表的标题添加到列表中。因此,当您在第二张工作表中查找要过滤的标题时,您会从第一张工作表中获取索引,因为IndexOf将首先出现。

此外,您似乎仅使用histoPlot(histo1,fmt=',')` histoPlot(histo2,fmt=',') 列表来过滤列,因此可以简化:

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  warnings.warn(message, mplDeprecation, stacklevel=1)