read objects from an excel sheet in csharp

To read objects from an Excel sheet in C#, you can use the Open XML SDK library. Here are the steps to accomplish this:

  1. Install the "DocumentFormat.OpenXml" NuGet package in your C# project.

  2. Import the required namespaces:

main.cs
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
82 chars
3 lines
  1. Open the Excel file using the SpreadsheetDocument class:
main.cs
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open("path_to_excel_file.xlsx", false))
{
    // Read the workbook part
    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
    
    // Get the first worksheet
    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
    
    // Get the sheet data
    SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();

    // Iterate through each row in the sheet
    foreach (Row row in sheetData.Elements<Row>())
    {
        // Iterate through each cell in the row
        foreach (Cell cell in row.Elements<Cell>())
        {
            // Read the cell value
            string cellValue = cell.CellValue.InnerText;
            
            // Do something with the cell value
            Console.WriteLine(cellValue);
        }
    }
}
852 chars
26 lines

This code will read each cell value from the first worksheet in the Excel file. You can modify it to suit your specific requirements, such as reading specific columns or cells.

Make sure to replace "path_to_excel_file.xlsx" with the actual path to your Excel file.

Note that this code assumes that the Excel file you are reading is in the Open XML Spreadsheet format (.xlsx). For other formats like .xls, you might need to use a different library or approach.

related categories

gistlibby LogSnag