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!