8

我处于不同寻常的位置,有两个不同的 Excel 上传模板,一个是“人类友好”的,一个是机器生成的。因此,列数据标题是不同的,很难对齐它们。

因此,我想使用序号位置而不是列的“名称”来引用列映射。目前我有这个:

var excel = new ExcelQueryFactory(excelFileName);
excel.AddMapping<Student>(x => x.FirstName, "First Name");
excel.AddMapping<Student>(x => x.LastName, "Last Name");
excel.AddMapping<Student>(x => x.LastFour, "Last 4 Student ID");
excel.AddMapping<Student>(x => x.LastDate, "Last Date");

我想做这样的事情:

var excel = new ExcelQueryFactory(excelFileName);
excel.AddMapping<Student>(x => x.FirstName, "A");
excel.AddMapping<Student>(x => x.LastName, "C");
excel.AddMapping<Student>(x => x.LastFour, "G");
excel.AddMapping<Student>(x => x.LastDate, "H");

其中字母是 Excel 中的列引用。

有没有办法做到这一点?

4

3 回答 3

14

如果你的订单是一样的,你可以打电话

        var columnnames= excel.GetColumnNames("worksheetName");
        excel.AddMapping<Student>(x => x.FirstName, columnnames[0]);
        excel.AddMapping<Student>(x => x.FirstName, columnnames[1]);
        excel.AddMapping<Student>(x => x.LastFour, columnnames[2]);
于 2014-06-04T21:36:08.387 回答
7

使用该WorksheetNoHeader方法是您正在寻找的。这是一个代码示例:

var students = new List<Student>();
var excel = new ExcelQueryFactory("excelFileName");
var rows = excel.WorksheetNoHeader().ToList();

//Skip the first row since it's the header
for (int rowIndex = 1; i < rows.Count; rowIndex++)
{
  var row = rows[rowIndex];
  var student = new Student();
  // row[0] refers to the value in the first column of the row
  student.FirstName = row[0];
  student.LastName = row[1];
  student.LastFour = row[2];
  student.LastDate = row[3];
  students.Add(student);
}
于 2014-06-04T22:07:06.927 回答
1

据我所见,您在人性化的列名和序数字母之间有一个 1 对 1 的映射。我的建议是尝试实现 a Dictionary<string,string>,其中键是列名,值是 Excel 中的列字母。当然,字典只需要初始化一次,所以可能通过单例,或者作为静态只读对象。

//Initialize dictionary
Dictionary<string,string> columnHeaders=new Dictionary<string,string>();
columnHeaders.Add("First Name", "A");
columnHeaders.Add("Last Name", "C");
columnHeaders.Add("Last 4 Student ID", "G");
columnHeaders.Add("Last Date", "H");

那么你的电话将是

var excel = new ExcelQueryFactory(excelFileName);
excel.AddMapping<Student>(x => x.FirstName, columnHeaders["First Name"]);
excel.AddMapping<Student>(x => x.LastName, columnHeaders["Last Name"]);
excel.AddMapping<Student>(x => x.LastFour, columnHeaders["Last 4 Student ID"]);
excel.AddMapping<Student>(x => x.LastDate, columnHeaders["Last Date"]);
于 2014-06-04T21:31:47.830 回答