read excel files with officeopenxml in csharp

You could use the OpenXml library to read and manipulate Excel files. Here is an example code to read the content of an Excel file:

main.cs
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

public static List<List<string>> ReadExcelFile(string filePath)
{
    List<List<string>> rows = new List<List<string>>();

    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filePath, false))
    {
        WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
        SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();

        foreach (Row row in sheetData.Elements<Row>())
        {
            List<string> cells = new List<string>();

            foreach (Cell cell in row.Elements<Cell>())
            {
                cells.Add(GetCellValue(workbookPart, cell));
            }

            rows.Add(cells);
        }
    }

    return rows;
}

private static string GetCellValue(WorkbookPart workbookPart, Cell cell)
{
    SharedStringTablePart sharedStringPart = workbookPart.SharedStringTablePart;

    if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
    {
        return sharedStringPart.SharedStringTable.ChildElements[Int32.Parse(cell.InnerText)].InnerText;
    }
    else
    {
        return cell.InnerText;
    }
}
1278 chars
43 lines

To use this method, call ReadExcelFile("path/to/excel/file").

The method returns a list of rows, where each row is represented by a list of strings representing the cells.

related categories

gistlibby LogSnag