我想根据我在工作表中指定的标题从 Excel 工作表中提取数据。我正在使用 ClosedXML 并使用单元格 Number.Below 获取数据。下面是我的代码。
FileInfo fi = new FileInfo(path1);
//Open uploaded workbook
var workBook = new XLWorkbook(fi.FullName);
//Get the first sheet of workbook
var worksheet = workBook.Worksheet(1);
var firstRowUsed = worksheet.FirstRowUsed();
var categoryRow = firstRowUsed.RowUsed();
/Get the column names from first row of excel
Dictionary<int, string> keyValues = new Dictionary<int,string>();
for (int cell = 1; cell <= categoryRow.CellCount(); cell++)
{
keyValues.Add(cell, categoryRow.Cell(cell).GetString());
}
//Get the next row
categoryRow = categoryRow.RowBelow();
while (!categoryRow.Cell(coCategoryId).IsEmpty())
{
int count = 1;
var pc = new ExpandoObject();
while (count <= categoryRow.CellCount())
{
// let this go through-if the data is bad, it will be rejected by SQL
var data = categoryRow.Cell(count).Value;
((IDictionary<string, object>)pc).Add(keyValues[count], data);
//((IDictionary<string, object>)pc).Add(keyValues[count], data);
fName = categoryRow.Cell(1).Value.ToString();
lName = categoryRow.Cell(2).Value.ToString();
userGender = categoryRow.Cell(3).Value.ToString();
roleTitle = categoryRow.Cell(4).Value.ToString();
mobileNumber = categoryRow.Cell(5).Value.ToString();
CurrentCity = categoryRow.Cell(6).Value.ToString();
country = categoryRow.Cell(7).Value.ToString();
birthDate = DateTime.UtcNow.ToLocalTime();
这是现在我想根据 excel 表中的字段名称提取数据的代码,如姓名、姓氏、城市 ....等等。如何做到这一点。