How can I read the contents of an Excel file using C#?

To read the content of an Excel file, you can utilize the Microsoft.Office.Interop.Excel library in C#.

Firstly, you need to reference the Microsoft.Office.Interop.Excel library in the project. Right-click on the project, select “Add” -> “Reference”, then in the “COM” tab, locate “Microsoft Excel xx.x Object Library”, check it, and click “OK”.

Here is a simple sample code demonstrating how to read the contents of an Excel file.

using System;
using Excel = Microsoft.Office.Interop.Excel;

namespace ReadExcelFile
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建Excel应用程序对象
            Excel.Application excelApp = new Excel.Application();

            // 打开Excel文件
            Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\path\to\your\excelFile.xlsx");

            // 获取第一个工作表
            Excel.Worksheet worksheet = workbook.Sheets[1];

            // 获取第一个工作表中的单元格A1的值
            Excel.Range range = worksheet.Cells[1, 1];
            string cellValue = range.Value2.ToString();

            // 输出单元格的值
            Console.WriteLine(cellValue);

            // 关闭Excel文件和应用程序对象
            workbook.Close();
            excelApp.Quit();
        }
    }
}

In the code, an Excel application object excelApp is first created, then an Excel file is opened using the Workbooks.Open() method to access the first worksheet. Next, the Cells[row, column] method is used to obtain a cell object range, and the Value2 property is used to retrieve the value of the cell.

Finally, close the Excel file and application object to release resources.

Please note that the code provided here is just a simple example. In real-world applications, error handling and processing multiple worksheets may be required.

bannerAds