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 packageto 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
-
Add a NuGet package: Install one of these in your project:
Microsoft.Office.Interop.Excel(for native Excel reading) orClosedXML(modern, lightweight). Use the NuGet Package Manager window in Visual Studio or run:dotnet add package ClosedXML(for ClosedXML). -
For Interop (Excel Native):
- Open Excel and note its full name (e.g., "C:\Files\Sheet.xlsx").
- Add using directives in your C# code:
using Microsoft.Office.Interop.Excel;using System.Runtime.InteropServices;using System.Windows.Forms; - Create an Excel Application object:
Excel.Application excelApp = new Excel.Application(); - Open the workbook:
Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\Files\Sheet.xlsx"); - 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(); } } - Close gracefully:
workbook.Close(); excelApp.Quit(); Marshal.ReleaseComObject(excelApp); // Important to avoid memory leaks!
-
For ClosedXML (Recommended):
- Install
ClosedXMLvia NuGet. - Load the workbook:
var workbook = new XLWorkbook(@"C:\Files\Sheet.xlsx"); - Access a worksheet:
var worksheet = workbook.Worksheet("Sheet1"); - 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(); } }
- Install
Common Mistakes
-
Excel crashes: Close Excel manually first or set
Application.DisableEvents = true;before opening. UseClosedXMLfor 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 restoreafter 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
StreamReaderfor .xlsx files. -
Error handling: Wrap code in try-catch:
try { ... } catch (Exception ex) { Console.WriteLine(ex.Message); } -
Modern .NET: For .NET 6+, use
OpenXmlSdkfor XLSX manipulation (better than ClosedXML for advanced tasks).
Troubleshooting
-
Excel App won't open:
Check Excel is installed and running. Add this to prevent crashes:
excelApp.Visible = false;Then close it withexcelApp.Quit(); -
ClosedXML fails to read:
Verify the file path is correct. Try a sample like
new XLWorkbook("test.xlsx"). -
Null values in data:
Use
?.ToString() ?? "Default"or parse numeric strings asdouble.TryParse(). -
Performance lag:
For ClosedXML, set
worksheet.CellStyle.Font.Size = 0to disable rendering. For Interop, setexcelApp.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 IEnumerabledouble 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.