使用序号位置引用LinqToExcel中的列

Bil*_*mpf 7 c# asp.net excel linq-to-excel

我处于不寻常的位置,有两个不同的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");
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情:

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");
Run Code Online (Sandbox Code Playgroud)

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

有没有办法做到这一点?

COL*_*OLD 11

如果你的订单是相同的,你可以打电话

        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]);
Run Code Online (Sandbox Code Playgroud)

  • @BillSempf我知道我迟到了,但是为了解决`ElementAt()`问题你可以在`GetColumnNames()之后一直调用`ToList()`,不是吗? (2认同)

Pau*_*aul 6

使用该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);
}
Run Code Online (Sandbox Code Playgroud)