gpt4 book ai didi

c# - 在 DataGridView 中读取 CSV 文件

转载 作者:太空狗 更新时间:2023-10-30 00:18:33 25 4
gpt4 key购买 nike

我想将 csv 文件读入 Datagridview。我想要一个像这样读取 csv 的类和函数:

class Import
{
public DataTable readCSV(string filePath)
{
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(filePath))
{
string strLine = sr.ReadLine();

string[] strArray = strLine.Split(';');

foreach (string value in strArray)
{
dt.Columns.Add(value.Trim());
}
DataRow dr = dt.NewRow();

while (sr.Peek() >= 0)
{
strLine = sr.ReadLine();
strArray = strLine.Split(';');
dt.Rows.Add(strArray);
}
}
return dt;
}
}

并调用它:

Import imp = new Import();

DataTable table = imp.readCSV(filePath);
foreach(DataRow row in table.Rows)
{
dataGridView.Rows.Add(row);
}

结果是->创建了行,但单元格中没有数据!!

最佳答案

使用一点 linq 的第一个解决方案

public DataTable readCSV(string filePath)
{
var dt = new DataTable();
// Creating the columns
File.ReadLines(filePath).Take(1)
.SelectMany(x => x.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
.ToList()
.ForEach(x => dt.Columns.Add(x.Trim()));

// Adding the rows
File.ReadLines(filePath).Skip(1)
.Select(x => x.Split(';'))
.ToList()
.ForEach(line => dt.Rows.Add(line));
return dt;
}

低于另一个使用 foreach 循环的版本

public DataTable readCSV(string filePath)
{
var dt = new DataTable();
// Creating the columns
foreach(var headerLine in File.ReadLines(filePath).Take(1))
{
foreach(var headerItem in headerLine.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
dt.Columns.Add(headerItem.Trim());
}
}

// Adding the rows
foreach(var line in File.ReadLines(filePath).Skip(1))
{
dt.Rows.Add(x.Split(';'));
}
return dt;
}

首先我们使用 File.ReadLines,它返回一个 IEnumerable,它是行的集合。我们使用 Take(1) 来获取第一行,这应该是标题,然后我们使用 SelectMany 将 Split 方法返回的字符串数组转换为一个列表,所以我们调用 ToList 现在我们可以使用 ForEach 方法在 DataTable 中添加列。

要添加行,我们仍然使用 File.ReadLines,但现在我们 Skip(1),这会跳过标题行,现在我们将使用 Select,创建一个 Collection<Collection<string>> ,然后再次调用 ToList,最后调用 ForEach 将行添加到 DataTable 中。 File.ReadLines 在 .NET 4.0 中可用。

观察: File.ReadLines不读取所有行,它返回一个 IEnumerable,并且对行进行惰性求值,因此仅第一行将被加载两次。

See the MSDN remarks

The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

You can use the ReadLines method to do the following:

Perform LINQ to Objects queries on a file to obtain a filtered set of its lines.

Write the returned collection of lines to a file with the File.WriteAllLines(String, IEnumerable) method, or append them to an existing file with the File.AppendAllLines(String, IEnumerable) method.

Create an immediately populated instance of a collection that takes an IEnumerable collection of strings for its constructor, such as a IList or a Queue.

This method uses UTF8 for the encoding value.

如果您仍有任何疑问,请查看此答案:What is the difference between File.ReadLines() and File.ReadAllLines()?

使用 CsvHelper 包的第二种解决方案

首先,安装这个nuget包

PM> Install-Package CsvHelper 

对于给定的 CSV,我们应该创建一个类来表示它

CSV 文件

Name;Age;Birthdate;Working
Alberto Monteiro;25;01/01/1990;true
Other Person;5;01/01/2010;false

类模型是

public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthdate { get; set; }
public bool Working { get; set; }
}

现在让我们使用 CsvReader 来构建数据表

public DataTable readCSV(string filePath)
{
var dt = new DataTable();

var csv = new CsvReader(new StreamReader(filePath));
// Creating the columns
typeof(Person).GetProperties().Select(p => p.Name).ToList().ForEach(x => dt.Columns.Add(x));

// Adding the rows
csv.GetRecords<Person>().ToList.ForEach(line => dt.Rows.Add(line.Name, line.Age, line.Birthdate, line.Working));
return dt;
}

要在 DataTable 中创建列,请使用一些反射,然后使用方法 GetRecords 在 DataTabble 中添加行

关于c# - 在 DataGridView 中读取 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34612021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com