将数据从 CSV 读取到 .net DataTable
我有一个要求,我必须从存储在磁盘中的 CSV 文件中读取数据,并将 CSV 中的所有数据放入 .Net DataTable 中。
我该怎么做呢?
I have a requirement where I have to read data from a CSV file which is stored in my disk and put all the data in the CSV into a .Net DataTable.
How can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
code-project 上的 FastCsvReader 做得很好; IIRC 它应该只是:(
但这是从记忆中)
The FastCsvReader on code-project does this very nicely; IIRC it should just be:
(but that is from memory)
有关于此问题的线程在 Microsoft 论坛上,它使用 CSV 文件的数据连接字符串,这可能是最简单/最快的方法。
或者,您可以一次读取一行文件,并为每一行创建一个 DataRow,将其添加到 DataTable 中。这是更多的手动工作,并且可能需要您对文件做出假设(列数、列名、数据类型等),但如果它只是针对一个已知文件,那么这应该不是一个大问题。
There's a thread about this on Microsoft's forums which uses a data connection string to the CSV file, which is probably the easiest/quickest way to do it.
Alternatively, you can read the file in one line at a time and create a DataRow for each line, adding it to the DataTable. That's more manual work, and may require you to make assumptions about the file (number of columns, column names, data types, etc.) but if it's just for one known file then that shouldn't be a big problem.
尝试Filehelpers。它将帮助您将数据以及强类型对象放入数据表中
Try Filehelpers. It will help you get your data into the datatable, as well as strong typed objects
我在下面编写了五种将 Csv 文件转换为 DataTable 的方法。
它们的设计考虑了可选的引号(例如“符号),并且在不使用其他库的情况下尽可能通用:
如果像我一样,您正在从报告服务中节省费用,那么您应该像这样使用它:
否则,您所需要做的就是:
或直接使用 csv 文件
或使用远程存储的 csv 文件
I have written five methods below that will turn a Csv file into a DataTable.
They have been designed to take into account optional quote marks (e.g. " symbols) and to be as versatile as possible without using other libraries:
If, like me, you're saving from reporting services then you should use it like this:
Otherwise, all you need do is:
Or to use directly from a csv file
Or to use a csv file that is stored remotely