To extract data from Excel files in C#, you’ll use built-in libraries like Microsoft.Office.Interop.Excel (for version 2016+) or ClosedXML (for modern .NET). The first reads Excel natively but requires Excel installed; the second is lightweight and works without it. Yes, you can read Excel files in C#—the simplest way is to install the Microsoft.Office.Interop.Excel assembly via NuGet, then loop through rows and columns to parse values. For modern projects, ClosedXML is faster and easier, supporting .xlsx/.xls formats without interop overhead.

What You'll Need

  • Visual Studio 2022+ or a .NET SDK (e.g., .NET 6/7/8).
  • NuGet Package Manager or dotnet add package to install libraries.
  • For Microsoft.Office.Interop.Excel, Excel 2016+ installed on Windows (required for interop).
  • For ClosedXML, no Excel needed—just a .NET project.
  • Sample Excel file (.xlsx or .xls) to test with.

Step-by-Step

  1. Add a NuGet package: Install one of these in your project: Microsoft.Office.Interop.Excel (for native Excel reading) or ClosedXML (modern, lightweight). Use the NuGet Package Manager window in Visual Studio or run: dotnet add package ClosedXML (for ClosedXML).
  2. For Interop (Excel Native):
    1. Open Excel and note its full name (e.g., "C:\Files\Sheet.xlsx").
    2. Add using directives in your C# code: using Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; using System.Windows.Forms;
    3. Create an Excel Application object: Excel.Application excelApp = new Excel.Application();
    4. Open the workbook: Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\Files\Sheet.xlsx");
    5. Loop through sheets and cells: for (int row = 1; row <= workbook.Sheets[1].Rows.Count; row++) { for (int col = 1; col <= workbook.Sheets[1].Columns.Count; col++) { string value = workbook.Sheets[1].Cells[row, col].Value.ToString(); } }
    6. Close gracefully: workbook.Close(); excelApp.Quit(); Marshal.ReleaseComObject(excelApp); // Important to avoid memory leaks!
    Warning: Excel interop can be slow and crash if Excel is not running. Prefer ClosedXML for performance.
  3. For ClosedXML (Recommended):
    1. Install ClosedXML via NuGet.
    2. Load the workbook: var workbook = new XLWorkbook(@"C:\Files\Sheet.xlsx");
    3. Access a worksheet: var worksheet = workbook.Worksheet("Sheet1");
    4. Loop through cells: for (int row = 1; row <= worksheet.Dimension.Rows; row++) { for (int col = 1; col <= worksheet.Dimension.Columns; col++) { var cellValue = worksheet.Cell(row, col).Value?.ToString(); } }
    Advantage: Works without Excel installed; faster for large files.

Common Mistakes

  • Excel crashes: Close Excel manually first or set Application.DisableEvents = true; before opening. Use ClosedXML for stability in production.
  • Null reference errors: Always check if a cell has a value: var value = worksheet.Cell(row, col).Value?.ToString() ?? "Empty";
  • Interop assembly errors: Ensure Excel is installed (check NuGet "Microsoft.Office.Interop.Excel" requires Office). Use dotnet restore after installation.
  • Wrong sheet name: Worksheets are 1-indexed (first sheet = Sheet1). List sheets first: workbook.Worksheets.ToList() in ClosedXML.

Tips

  • Optimize ClosedXML: Use worksheet.Range("A1:Z1000") to read specific columns/rows instead of looping.
  • Handle large files: Process in chunks or use StreamReader for .xlsx files.
  • Error handling: Wrap code in try-catch: try { ... } catch (Exception ex) { Console.WriteLine(ex.Message); }
  • Modern .NET: For .NET 6+, use OpenXmlSdk for XLSX manipulation (better than ClosedXML for advanced tasks).

Troubleshooting

  1. Excel App won't open: Check Excel is installed and running. Add this to prevent crashes: excelApp.Visible = false; Then close it with excelApp.Quit();
  2. ClosedXML fails to read: Verify the file path is correct. Try a sample like new XLWorkbook("test.xlsx").
  3. Null values in data: Use ?.ToString() ?? "Default" or parse numeric strings as double.TryParse().
  4. Performance lag: For ClosedXML, set worksheet.CellStyle.Font.Size = 0 to disable rendering. For Interop, set excelApp.DisplayAlerts = false; to skip save prompts.

Frequently Asked Questions

How do I read a specific column in ClosedXML?

Use worksheet.Column("A").Values to get all values in column A as an IEnumerable. For numeric columns, cast to double or int before processing.

Can I use this in a web app (ASP.NET Core)?

Yes, but avoid Microsoft.Office.Interop.Excel due to dependency on Excel. Use ClosedXML or OpenXmlSdk instead. For server-side processing, consider streaming data from Excel using ExcelFile from ClosedXML.

Why does my code throw "COMException: Cannot open file"?

This occurs if Excel is not installed (for Interop) or the file path is invalid. Double-check: 1. File exists at the path. 2. File is not corrupted (try opening it in Excel manually). 3. For ClosedXML, ensure the filename is correct (e.g., @"C:\Data.xlsx", not C:\Data.xlsx).

How do I export processed data back to Excel?

Use ClosedXML’s Worksheet.SaveAs() method: worksheet.SaveAs(@"output.xlsx"); For Interop, use workbook.SaveAs(@"output.xlsx", Excel.XlFileFormat.xlWorkbookNormal);

Is there a way to read encrypted Excel files?

For ClosedXML, encrypted files require the password. Add this before opening: workbook.Password = "your_password"; For Interop, use excelApp.Workbooks.Open(@"C:\file.xlsx", false, true, "password");

How do I handle date values from Excel?

Excel stores dates as serial numbers. Convert them to readable dates in C#: DateTime dateValue = DateTime.FromOADate(worksheet.Cell(row, col).Value); For ClosedXML, use DateTime.FromOADate(worksheet.Cell(row, col).Value).

Need to parse formulas or advanced formulas? Use worksheet.Cell(row, col).Formula in ClosedXML to extract raw formulas.