我的问题是如何过滤列的内容。 我有一个像'Spinbase TrackingState'这样的专栏,我有两个选项'跟踪'和'未跟踪' 我想加载,其中只包括'Tracked'。 谢谢你的帮助!:)
namespace LoadFromCsv
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public DataTable ReadCsv(string filePath)
{
var dt = new DataTable();
List<string> cols = File.ReadLines(filePath).Take(1)
.SelectMany(x => x.Split(new[] { ';' }))
.ToList();
for (int i = 0; i < cols.Count; i++)
{
string colName = cols[i].Trim();
//Debug.Print(colName);
int num = 1;
for (int j = i+1; j < cols.Count; j++)
{
if (cols[i] == cols[j])
{
//Debug.Print(string.Format("({0},{1})", i, j));
cols[j] = string.Format("{0}_{1}", cols[i], ++num);
Debug.Print(string.Format("{0} -> {1}", cols[i], cols[j]));
}
}
/*
while (dt.Columns.Contains(colName))
{
Debug.Print(string.Format("{0} -> {1}", num, colName));
colName = string.Format("{0}_{1}", cols[i], ++num);
Debug.Print(colName);
}
dt.Columns.Add(colName.Trim());
//cols[i] = colName;
*/
}
cols.ForEach(x => dt.Columns.Add(x.Trim()));
File.ReadLines(filePath).Skip(1)
.Select(x => x.Split(';'))
.ToList()
.ForEach(line => dt.Rows.Add(line));
return dt;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV|*.csv", ValidateNames = true, Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
dataGridView1.DataSource = ReadCsv(ofd.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}