Home > Backend Development > C++ > How Can I Read Excel Files in C# Using ClosedXML or ACE?

How Can I Read Excel Files in C# Using ClosedXML or ACE?

Mary-Kate Olsen
Release: 2025-02-01 11:26:11
Original
656 people have browsed it

How Can I Read Excel Files in C# Using ClosedXML or ACE?

Reading Excel Files from C#

Reading Excel files directly from a C# program can be accomplished using a third-party library. One popular option is the ClosedXML library, an open-source and free tool for reading and writing Excel files. It provides a comprehensive set of features to manage spreadsheets, including the ability to:

  • Open and read Excel files (.xls and .xlsx)
  • Select specific worksheets within a file
  • Read and modify cell values as strings, numbers, or other data types
  • Retrieve cell formulas and formatting information

To use ClosedXML in your C# program:

using ClosedXML.Excel;

var fileName = "myExcelFile.xlsx";
using (var workbook = new XLWorkbook(fileName))
{
    var worksheet = workbook.Worksheet("MyWorksheet");
    var data = worksheet.Range("A1:C10").Value;
}
Copy after login

Another option for reading Excel files is to use ACE (Access Database Engine), which supports reading Excel files through an OLE DB connection:

var fileName = "myExcelFile.xlsx";
var connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;";
using (var connection = new OleDbConnection(connectionString))
{
    connection.Open();
    var command = new OleDbCommand("SELECT * FROM [Sheet1$]", connection);
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            var data1 = reader[0].ToString();
            var data2 = reader[1].ToString();
            // Process the data
        }
    }
}
Copy after login

Regardless of the library chosen, these solutions allow for efficient reading and processing of Excel files from a C# program.

The above is the detailed content of How Can I Read Excel Files in C# Using ClosedXML or ACE?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template