以下是我用于在WinForms应用程序中将CSV文件加载到DataGridView中的代码:
private void loadCSV(string path)
{
if (!File.Exists(path))
{
MessageBox.Show(this, "File does not exist:\r\n" + path, "No File", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
try
{
string conStr = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=C:;Extensions=csv,txt";
OdbcConnection conn = new OdbcConnection(conStr);
OdbcDataAdapter da = new OdbcDataAdapter("Select * from " + path, conn);
dt = new DataTable(path);
da.Fill(dt);
this.path = path;
dataGridView.DataSource = dt;
da.Dispose();
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(this, "There was an error loading the CSV file:\r\n" + ex.Message, "IO Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
它可以处理几乎所有有效的CSV文件,但在包含某些字符的文件夹中的文件除外。
例如,它可以处理:
- C:\Users\Public\Desktop\MyCSV.csv
但是无法处理:
- C:\Users\Public\Desktop\My Folder\MyCSV.csv
有人知道怎么解决吗?我猜我需要以某种方式增强conStr。