嗨,我正在尝试使用 .Net core 使用 open xml 读取 excel。我有下面的代码,我能够显示单元格值,但我期望的是我想读类似的内容
行:0和列:0和单元格值:某个值
所以基本上我想根据每行和列的详细信息显示单元格值。
private DataTable ConvertExcelToDataTable(IFormFile uploadRegistration)
{
//Create a new DataTable.
var table = new DataTable();
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(uploadRegistration.OpenReadStream(), false))
{
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
SheetData sheetData = workSheet.GetFirstChild<SheetData>();
IEnumerable<Row> rows = sheetData.Descendants<Row>();
foreach (Cell cell in rows.ElementAt(0))
{
table.Columns.Add(GetCellValue(spreadSheetDocument, cell));
}
foreach (Row row in rows)
{
DataRow tempRow = table.NewRow();
for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
{
// tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
Console.WriteLine(GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i))); // Here i am able to display cell value but not row and column details
}
table.Rows.Add(tempRow);
}
}
table.Rows.RemoveAt(0);
return table;
}
在上面的代码中,我可以使用但与我想要显示的对应行和列的单元格值一起显示单元格值,有人可以帮助我如何访问行和列。任何帮助将不胜感激谢谢
Console.WriteLine(GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i)));
Cell 有一个名为 CellReference 的属性,其中包含“A1”形式的单元格地址。由此您可以计算列和行索引,如下所示:
public static void ParseCellAddress(string s)
{
StringBuilder stringBuilderCol = new StringBuilder();
StringBuilder stringBuilderRow = new StringBuilder();
foreach (char c in s)
{
if (char.IsLetter(c))
{
if (stringBuilderRow.Length > 0)
{
throw new ArgumentException($"Invalid cell address {s}.");
}
stringBuilderCol.Append(c);
}
else if (char.IsDigit(c))
{
if (stringBuilderCol.Length < 1)
{
throw new ArgumentException($"Invalid cell address {s}.");
}
stringBuilderRow.Append(c);
}
else
{
throw new ArgumentException($"Invalid cell address {s}.");
}
}
if (stringBuilderRow.Length == 0 || stringBuilderCol.Length == 0)
{
throw new ArgumentException($"Invalid cell address {s}.");
}
int rowIdx = int.Parse(stringBuilderRow.ToString());
// calc column index from column name
string columnName = stringBuilderCol.ToString();
int number = 0;
int pow = 1;
for (int i = columnName.Length - 1; i >= 0; i--)
{
number += (columnName[i] - 'A' + 1) * pow;
pow *= 26;
}
int colIdx = number;
}