Microsoft Excel is a popular tool for working with tabular data, and sometimes, you may need to automate the process of reading data from Excel files in your C# applications. In this tutorial, we will walk you through the process of reading an MS Excel file using C#.
Prerequisites:
Before we dive into the code, make sure you have the following prerequisites in place:
1)Visual Studio: You need a development environment like Visual Studio to write and run C# code.
2)Microsoft.Office.Interop.Excel: This library is used for interacting with Excel files. You can add it to your project using NuGet Package Manager.
In your C# code, add the necessary namespace for working with Excel:
- using Excel = Microsoft.Office.Interop.Excel;
Read Excel File
Below write code to read an Excel file. In this example, we assume that you have an Excel file named "sample.xlsx" in your project directory.
- class Program
- {
- static void Main(string[] args)
- {
- // Create an Excel application instance
- Excel.Application excelApp = new Excel.Application();
- // Open the Excel workbook
- Excel.Workbook workbook = excelApp.Workbooks.Open(@"Path\to\your\sample.xlsx");
- // Get the first worksheet (index 1)
- Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1];
- // Get the used range of the worksheet
- Excel.Range usedRange = worksheet.UsedRange;
- // Loop through the rows and columns to read data
- int rowCount = usedRange.Rows.Count;
- int colCount = usedRange.Columns.Count;
- for (int i = 1; i <= rowCount; i++)
- {
- for (int j = 1; j <= colCount; j++)
- {
- // Read cell value
- string cellValue = usedRange.Cells[i, j].Value2.ToString();
- Console.Write(cellValue + "\t");
- }
- Console.WriteLine();
- }
- // Close Excel workbook and application
- workbook.Close();
- excelApp.Quit();
- // Release COM objects
- Marshal.ReleaseComObject(usedRange);
- Marshal.ReleaseComObject(worksheet);
- Marshal.ReleaseComObject(workbook);
- Marshal.ReleaseComObject(excelApp);
- Console.WriteLine("Excel file read successfully.");
- }
- }
Run the Application
Build and run your C# application. It will open the Excel file, read its contents, and display them in the console.

Post a Comment
0Comments