首页 >后端开发 >C++ >如何使用免费和开源库在C#中直接读取Excel文件?

如何使用免费和开源库在C#中直接读取Excel文件?

Susan Sarandon
Susan Sarandon原创
2025-02-01 11:41:10819浏览

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

>使用开源工具直接读取C#中的Excel文件

c#开发人员经常需要从其应用程序中的Excel文件直接读取数据。本指南演示了如何使用免费和开源库有效地实现此目的。

>

>一种流行的方法利用OLEDB。 以下代码片段说明了连接到Excel文件,选择工作表并将数据检索为字符串:

>

<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>
用于流线型数据操作,利用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>
>这种方法提供了一种简单有效的方法来访问Excel数据,消除了对手动导出的需求和随后的解析。

>

以上是如何使用免费和开源库在C#中直接读取Excel文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn