正在将CSV加载到DataGridView中

本文关键字:DataGridView 加载 CSV | 更新日期: 2023-09-27 17:59:38

以下是我在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: ''用户''公用''桌面''MyCSV.csv

但不适用于

  • C: ''用户''公用''桌面''我的文件夹''MyCSV.csv

有人知道我该怎么修吗?我想我需要以某种方式增强conStr。

正在将CSV加载到DataGridView中

将选择语句更改为

OdbcDataAdapter da = new OdbcDataAdapter("Select * from [" + path + "]", conn);

文件名中的空格会将其注销。