Reading MS Excel Files in C# - A Step-by-Step Guide

Lawson Borges
By -
0

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:

  1. 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.

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         // Create an Excel application instance  
  6.         Excel.Application excelApp = new Excel.Application();  
  7.   
  8.         // Open the Excel workbook  
  9.         Excel.Workbook workbook = excelApp.Workbooks.Open(@"Path\to\your\sample.xlsx");  
  10.   
  11.         // Get the first worksheet (index 1)  
  12.         Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1];  
  13.   
  14.         // Get the used range of the worksheet  
  15.         Excel.Range usedRange = worksheet.UsedRange;  
  16.   
  17.         // Loop through the rows and columns to read data  
  18.         int rowCount = usedRange.Rows.Count;  
  19.         int colCount = usedRange.Columns.Count;  
  20.   
  21.         for (int i = 1; i <= rowCount; i++)  
  22.         {  
  23.             for (int j = 1; j <= colCount; j++)  
  24.             {  
  25.                 // Read cell value  
  26.                 string cellValue = usedRange.Cells[i, j].Value2.ToString();  
  27.                 Console.Write(cellValue + "\t");  
  28.             }  
  29.             Console.WriteLine();  
  30.         }  
  31.   
  32.         // Close Excel workbook and application  
  33.         workbook.Close();  
  34.         excelApp.Quit();  
  35.   
  36.         // Release COM objects  
  37.         Marshal.ReleaseComObject(usedRange);  
  38.         Marshal.ReleaseComObject(worksheet);  
  39.         Marshal.ReleaseComObject(workbook);  
  40.         Marshal.ReleaseComObject(excelApp);  
  41.   
  42.         Console.WriteLine("Excel file read successfully.");  
  43.     }  
  44. }  

Run the Application

Build and run your C# application. It will open the Excel file, read its contents, and display them in the console.

Tags:

Post a Comment

0Comments

Post a Comment (0)