C#数据存储到本地CSV文件Demo
时间: 2024-10-08 18:15:10 浏览: 176
在C#中,将数据存储到本地CSV(Comma Separated Values)文件是一种常见的操作,可以使用`System.IO.File`和`System.Text.Encoding`类来进行。下面是一个简单的示例,演示如何将列表转换为CSV并保存到文件:
```csharp
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
List<Employee> employees = GetSampleEmployees();
string filePath = "employees.csv";
SaveToCsv(employees, filePath);
Console.WriteLine("Data saved to CSV file successfully.");
}
static List<Employee> GetSampleEmployees()
{
return new List<Employee>
{
new Employee { Id = 1, Name = "Alice", Position = "Manager" },
new Employee { Id = 2, Name = "Bob", Position = "Developer" },
// 更多员工...
};
}
static void SaveToCsv(List<Employee> data, string filePath)
{
using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8))
{
// 写入表头
writer.WriteLine("ID,Name,Position");
// 写入行
foreach (Employee employee in data)
{
writer.WriteLine($"{employee.Id},{employee.Name},{employee.Position}");
}
}
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
}
}
```
在这个例子中,我们首先定义了一个`GetSampleEmployees()`方法生成一些模拟的员工数据,然后调用`SaveToCsv()`函数将这些数据以CSV格式写入指定文件。每个员工的数据一行,以逗号分隔。
阅读全文
相关推荐
















