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"];
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"), });
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!