c# 如何读取一个csv文件
时间: 2023-09-14 20:14:23 浏览: 99
在 C# 中,可以使用 System.IO 和 System.Data 命名空间中的类来读取 CSV 文件。以下是一个简单的例子:
```csharp
using System;
using System.IO;
using System.Data;
class Program
{
static void Main(string[] args)
{
// 读取 CSV 文件
string path = @"C:\data.csv";
DataTable table = new DataTable();
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] values = line.Split(',');
if (table.Columns.Count == 0)
{
// 添加列
foreach (string header in values)
{
table.Columns.Add(header);
}
}
else
{
// 添加行
DataRow row = table.NewRow();
for (int i = 0; i < values.Length; i++)
{
row[i] = values[i];
}
table.Rows.Add(row);
}
}
}
// 输出数据
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
Console.Write(item.ToString() + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
```
这个例子使用 StreamReader 读取 CSV 文件,然后使用 DataTable 存储数据。在读取文件时,它将每一行拆分成一个字符串数组,并根据第一行的列头添加列。然后,它使用 DataRow 对象添加每一行的数据。最后,它使用 foreach 循环输出 DataTable 中的数据。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![cs](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)