read an excel file in csharp

To read an Excel file in C#, you can use the Microsoft.Office.Interop.Excel library. Here's an example:

First, make sure you have added a reference to the Microsoft.Office.Interop.Excel assembly.

main.cs
using Excel = Microsoft.Office.Interop.Excel;

class Program
{
    static void Main(string[] args)
    {
        // Create an Excel application object
        Excel.Application excelApp = new Excel.Application();

        // Open the Excel file
        Excel.Workbook workbook = excelApp.Workbooks.Open("path_to_your_excel_file");

        // Get the first worksheet
        Excel.Worksheet worksheet = workbook.Sheets[1];

        // Get the used range of the worksheet
        Excel.Range range = worksheet.UsedRange;

        // Iterate over the cells in the range
        foreach (Excel.Range cell in range)
        {
            // Access the cell value
            string cellValue = cell.Value2.ToString();

            // Do something with the cell value
            Console.WriteLine(cellValue);
        }

        // Close the workbook and release resources
        workbook.Close();
        excelApp.Quit();
        Marshal.ReleaseComObject(worksheet);
        Marshal.ReleaseComObject(workbook);
        Marshal.ReleaseComObject(excelApp);
    }
}
1060 chars
37 lines

In this example, we create an Excel.Application object, then open the Excel file using the Workbooks.Open() method. We retrieve the first worksheet using the Sheets property and iterate over the cells in the used range of the worksheet using a foreach loop.

Remember to replace "path_to_your_excel_file" with the actual path to your Excel file.

Note that this approach requires the Excel application to be installed on the machine running the code. Alternatively, you can use third-party libraries like EPPlus or NPOI to read Excel files without the dependency on Excel itself.

related categories

gistlibby LogSnag