问题
I am trying to read some .xslx files with the open xml sdk, but I'm really struggeling finding any good examples.
What I want to do is to read the entire XSLX file and loop through all of the rows and extract the cellvalue/celltext from the columns i specify.
Like the following:
GetCellText(rowId, ColumnLetter)
Is this possible?
回答1:
Helpers:
private static string GetColumnName(string cellReference)
{
if (ColumnNameRegex.IsMatch(cellReference))
return ColumnNameRegex.Match(cellReference).Value;
throw new ArgumentOutOfRangeException(cellReference);
}
private static readonly Regex ColumnNameRegex = new Regex("[A-Za-z]+");
Code:
using (var document = SpreadsheetDocument.Open(stream, true))
{
var sheets = document.WorkbookPart.Workbook.Descendants<Sheet>();
foreach (Sheet sheet in sheets)
{
WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id);
Worksheet worksheet = worksheetPart.Worksheet;
var rows = worksheet.GetFirstChild<SheetData>().Elements<Row>();
foreach (var row in rows)
{
var cells = row.Elements<Cell>();
foreach (var cell in cells)
{
if(GetColumnName(cell.CellReference) == "A")
{
var str = cell.CellValue.Text;
// do whatewer you want
}
}
}
}
}
回答2:
Your question is similar to this one
1) Open xml excel read cell value
You can get the row by ID and look-up the value by column name.
Hope that helps
来源:https://stackoverflow.com/questions/13412143/how-to-read-xslx-with-open-xml-sdk-based-on-columns-in-each-row-in-c