示例:
public static DataTable dTable;
public bool openDBSheet(string sheet)
{
String str=
"Provider=Microsoft.ACE.OLEDB.12.0;"
+ @"Data Source=D:Item1.xlsx;"
+"Extended Properties='Excel 12.0 XML;HDR=Yes'";
try
{
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + sheet + "$]", conn);
dTable = new DataTable();
adapter.Fill(dTable);
conn.Close();
}
catch (Exception)
{
return false;
}
return true;
}
真正的文件名是"Item.xlsx",但是当我将路径更改为"D:\Item1.xlsx;"时(不存在(程序创建一个名为"Item1.xlsx"的新空文件。 谁能解释一下我为什么以及如何解决它?
或者,也许还有另一种更好的方法来验证不存在的 excel 文件 OLEDB ???
您可以使用File.Exists()
if (!File.Exists(@"D:Item1.xlsx"))
return;