在加载.
中有15.01.19.csv
的文件时,出现以下错误:
System.Data.OleDb.OleDbException:“ 15.01.19.csv”不是有效名称。确保它不包含无效字符或标点符号,并且时间不要太长。'
在线:
adapter.Fill(dataTable);
代码:
private DataTable FillData(string connection, string query)
{
DataTable dataTable = new DataTable();
using (OleDbConnection con = new OleDbConnection(connection))
{
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
adapter.Dispose();
};
return dataTable;
}
要导入文件的代码为:
private DataTable GetData(string userFileName)
{
string dirName = Path.GetDirectoryName(userFileName);
string fileName = Path.GetFileName(userFileName);
string fileExtension = Path.GetExtension(userFileName);
string connection = string.Empty;
string query = string.Empty;
switch (fileExtension)
{
case ".csv":
connection = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={dirName};" +
"Extended Properties=\"text; HDR=Yes; IMEX=1; FMT=Delimited\"";
query = $"SELECT * FROM {fileName}";
break;
}
return FillData(connection, query);
}
我尝试将正则表达式添加到字符串dirName = Path.GetDirectoryName(userFileName);
中,但这没用。
答案 0 :(得分:0)
我通过添加以下代码解决了这个问题:
string userFileName = Path.Combine(Path.GetDirectoryName(userFileNameUT), Path.GetFileNameWithoutExtension(userFileNameUT.Replace(".", "")) + ".csv");
File.Copy(userFileNameUT, userFileName, true);
在我的Browse
按钮上,单击:
private void Browse_Click(object sender, EventArgs e)
{
string userFileNameUT = string.Empty;
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.RestoreDirectory = true;
ofd.Filter = "CSV Files|*.csv|Excel '97-2003|*.xls|Excel 2007-2019|*.xlsx";
if (ofd.ShowDialog(this) == DialogResult.OK)
userFileNameUT = ofd.FileName;
}
string userFileName = Path.Combine(Path.GetDirectoryName(userFileNameUT), Path.GetFileNameWithoutExtension(userFileNameUT.Replace(".", "")) + ".csv");
File.Copy(userFileNameUT, userFileName, true);
if (userFileNameUT.Length == 0) return;
this.dataGridView1.DataSource = GetData(userFileName);
fileTextBox.Text = userFileName;
}