Home >Backend Development >C++ >How Can I Read Excel Files Directly in C# Using Free and Open Source Libraries?

How Can I Read Excel Files Directly in C# Using Free and Open Source Libraries?

Susan Sarandon
Susan SarandonOriginal
2025-02-01 11:41:10960browse

How Can I Read Excel Files Directly in C# Using Free and Open Source Libraries?

Directly Reading Excel Files in C# with Open-Source Tools

C# developers frequently need to read data directly from Excel files within their applications. This guide demonstrates how to achieve this efficiently using free and open-source libraries.

A popular method utilizes OLEDB. The following code snippet illustrates connecting to an Excel file, selecting a worksheet, and retrieving data as strings:

<code class="language-csharp">var fileName = string.Format("{0}\fileNameHere", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "anyNameHere");

DataTable data = ds.Tables["anyNameHere"];</code>

For streamlined data manipulation, leverage LINQ:

<code class="language-csharp">var data = ds.Tables["anyNameHere"].AsEnumerable();
var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x =>
                new MyContact
                    {
                        firstName= x.Field<string>("First Name"),
                        lastName = x.Field<string>("Last Name"),
                        phoneNumber =x.Field<string>("Phone Number"),
                    });</code>

This approach offers a simple and effective way to access Excel data, eliminating the need for manual export and subsequent parsing.

The above is the detailed content of How Can I Read Excel Files Directly in C# Using Free and Open Source Libraries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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