简体   繁体   English

如何从csv文件内容创建DataTable

[英]How to create DataTable from csv file content

我有包含* .csv文件内容的字符串数据(使用File.ReadAllText(filePath)方法读取,并希望从字符串数据中创建新的数据表对象。我没有使用文件路径的选项,因为该文件会立即删除读取驱动器中的数据。

You could consider replacing your File.ReadAllText method with File.ReadAllLines. 您可以考虑将File.ReadAllText方法替换为File.ReadAllLines。 Then, you could do something like the below steps: 然后,您可以执行以下步骤:

  1. Create a datatable, define its structure etc. 创建数据表,定义其结构等。
  2. Read all lines from file as an array of strings 从文件中读取所有行作为字符串数组
  3. In a loop, split the string by your separator character, then parse each portion of string as its corresponding datatype eg int.TryParse() for numerical values etc. 在循环中,用分隔符分割字符串,然后将字符串的每个部分解析为其对应的数据类型,例如int.TryParse()以获取数值等。
  4. Add new row to the datatable using DataTable.Rows.Add and supplying an object array with your parsed values. 使用DataTable.Rows.Add将新行添加到数据表中,并为对象数组提供解析后的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM