read excel files in csharp

To read an Excel file in C#, you can use the Microsoft.Office.Interop.Excel namespace. Here's a basic example of how to read the data from the first worksheet in an Excel file:

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

// Open the Excel file using the Open method of the Workbooks object
Workbook workbook = new Application().Workbooks.Open("path/to/excel/file.xlsx");

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

// Get the range of cells that have data
Range range = worksheet.UsedRange;

// Loop through the rows and columns of the data
for (int row = 1; row <= range.Rows.Count; row++)
{
    for (int column = 1; column <= range.Columns.Count; column++)
    {
        // Get the value of the current cell
        var value = (range.Cells[row, column] as Range).Value2;

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

// Close the workbook and release resources
workbook.Close();
768 chars
27 lines

This is just a basic example, and there are many other ways to read and work with Excel files in C#. You may also want to consider using a third-party library, such as EPPlus, which provides a more user-friendly API for working with Excel files in C#.

related categories

gistlibby LogSnag