C# 从csv文件(逗号分隔)导入两个或多个列数据,并使用c跳过第一行#
假设csv文件中有以下工作表,如下图所示: 我想将每列数据作为列表导入,并在visual studio中使用c#跳过第一行。 我还需要知道如何只浏览csv文件并使用c#加载它。C# 从csv文件(逗号分隔)导入两个或多个列数据,并使用c跳过第一行#,c#,visual-studio,C#,Visual Studio,假设csv文件中有以下工作表,如下图所示: 我想将每列数据作为列表导入,并在visual studio中使用c#跳过第一行。 我还需要知道如何只浏览csv文件并使用c#加载它。 提前感谢无需在CSV文件读取上重新发明轮子。通过NuGet安装CsvHelper,然后按照此处的说明使用: 这将避免您担心转义逗号、跳过标题行、处理非常大的文件等问题。实际上,您可以将csv文件视为txt文件。csv中的数据以以下格式保存(使用逗号作为分隔符) 所以您可以像读取.txt文件一样读取数据。至于“仅浏览cs
提前感谢无需在CSV文件读取上重新发明轮子。通过NuGet安装
CsvHelper
,然后按照此处的说明使用:
这将避免您担心转义逗号、跳过标题行、处理非常大的文件等问题。实际上,您可以将csv文件视为txt文件。csv中的数据以以下格式保存(使用逗号作为分隔符) 所以您可以像读取.txt文件一样读取数据。至于“仅浏览csv文件”,您可以为
OpenFileDialog
设置过滤器
这里是一个简单的演示
List<string> name = new List<string>();
List<string> id = new List<string>();
List<string> salary = new List<string>();
private void btOpenCSV_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open CSV";
ofd.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
ofd.InitialDirectory = "d:\\";
if (ofd.ShowDialog() == DialogResult.OK)
{
bool isfirstrow = true; // check if the first row
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((line = file.ReadLine()) != null)
{
if (isfirstrow)
{
isfirstrow = false;
continue;
}
name.Add(line.Split(',')[0]);
id.Add(line.Split(',')[1]);
salary.Add(line.Split(',')[2]);
}
}
}
List name=新列表();
列表id=新列表();
列表薪资=新列表();
私有void btOpenCSV_单击(对象发送方,事件参数e)
{
OpenFileDialog ofd=新建OpenFileDialog();
ofd.Title=“打开CSV”;
ofd.Filter=“CSV文件(*.CSV)|*.CSV|所有文件(*.*)|*.”;
ofd.InitialDirectory=“d:\\”;
if(ofd.ShowDialog()==DialogResult.OK)
{
bool isfirstrow=true;//检查第一行
弦线;
//读取文件并逐行显示。
System.IO.StreamReader文件=
新System.IO.StreamReader(ofd.FileName);
而((line=file.ReadLine())!=null)
{
如果(第一行)
{
isfirstrow=false;
持续
}
name.Add(line.Split(',')[0]);
id.Add(行分割(',')[1]);
添加(行分割(',')[2]);
}
}
}
此Nuget软件包将帮助您解析CSV文件:以下是一个示例:
List<string> name = new List<string>();
List<string> id = new List<string>();
List<string> salary = new List<string>();
private void btOpenCSV_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open CSV";
ofd.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
ofd.InitialDirectory = "d:\\";
if (ofd.ShowDialog() == DialogResult.OK)
{
bool isfirstrow = true; // check if the first row
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((line = file.ReadLine()) != null)
{
if (isfirstrow)
{
isfirstrow = false;
continue;
}
name.Add(line.Split(',')[0]);
id.Add(line.Split(',')[1]);
salary.Add(line.Split(',')[2]);
}
}
}