how to import excel file in csharp

Here's an example of how to import an Excel file in C# using Microsoft.Office.Interop.Excel:

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

// ...

Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(@"C:\path\to\file.xlsx");

Worksheet worksheet = workbook.ActiveSheet;

int rowCount = worksheet.UsedRange.Rows.Count;
int colCount = worksheet.UsedRange.Columns.Count;

for (int i = 1; i <= rowCount; i++)
{
    for (int j = 1; j <= colCount; j++)
    {
        Range range = worksheet.Cells[i, j];
        Console.Write(range.Value2 + "\t");
    }
    Console.WriteLine();
}

workbook.Close();
excel.Quit();
536 chars
25 lines

This code creates a new instance of the Excel application and opens the specified file. The code then gets the active sheet in the file and loops through each cell in the used range of the sheet, outputting the value of each cell to the console.

Note that you will need to add a reference to the Microsoft.Office.Interop.Excel assembly in your project before you can use this code.

related categories

gistlibby LogSnag