Home > Backend Development > C++ > How Can I Efficiently Read and Process Data from Excel Files Using C#?

How Can I Efficiently Read and Process Data from Excel Files Using C#?

Linda Hamilton
Release: 2025-02-01 11:31:12
Original
647 people have browsed it

How Can I Efficiently Read and Process Data from Excel Files Using C#?

Reading Excel Files in C#

Reading data directly from Excel files in C# can be an essential task in many development scenarios. To address this need, various free and open-source libraries are available to assist you. Here's a popular solution:

Utilizing the OleDbDataAdapter class from System.Data.OleDb, you can create a data source connection and retrieve data from an Excel worksheet. Here's a code sample:

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"];
Copy after login

To further enhance data manipulation, you can use the AsEnumerable() method to utilize LINQ for filtering and constructing custom structs.

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"),
                    });
Copy after login

By leveraging these techniques, you can effortlessly extract data from Excel files without the need for manual operations or dependency on external tools.

The above is the detailed content of How Can I Efficiently Read and Process Data from Excel Files Using C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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