To read an Excel 2007/2010 table with the OpenXML API is really enough. Somehow even easier than using OleDB, as we always did it as a quick and dirty solution. In addition, it is not easy, but detailed , I think that putting all the code here is not useful if you need to comment and explain it, so I will write only a summary and I will link a good article. Read this article on MSDN , which explains how to read XLSX documents very easily.
Summarize:
- Open
SpreadsheetDocument with SpreadsheetDocument.Open . - Get the
Sheet you need with the LINQ query from the WorkbookPart document. - Get (finally!)
WorksheetPart (the object you need) using the Sheet identifier.
In the code, removing comments and handling errors:
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) { Sheet sheet = document.WorkbookPart.Workbook .Descendants<Sheet>() .Where(s => s.Name == sheetName) .FirstOrDefault(); WorksheetPart sheetPart = (WorksheetPart)(document.WorkbookPart.GetPartById(theSheet.Id)); }
Now (but inside use!) You just need to read the cell value:
Cell cell = sheetPart.Worksheet.Descendants<Cell>(). Where(c => c.CellReference == addressName).FirstOrDefault();
If you need to list the rows (and there are many), you should first get a reference to the SheetData object:
SheetData sheetData = sheetPart.Worksheet.Elements<SheetData>().First();
Now you can query all rows and cells:
foreach (Row row in sheetData.Elements<Row>()) { foreach (Cell cell in row.Elements<Cell>()) { string text = cell.CellValue.Text;
To simply list a regular spreadsheet, you can use the Descendants<Row>() of the WorksheetPart object.
If you need more resources about OpenXML, check out OpenXML Developer , it contains many good lessons.
source share