无法在 c# 中打开 excel 文件,因为您尝试以与指定文件扩展名不同的格式打开的文件。在打开文件之前,请确认文件没有损坏并且来自受信任的来源。您现在要打开文件吗?
private void button1_Click(object sender, EventArgs e)
{
string fileName = Directory.GetCurrentDirectory();
fileName += "\\" + textBox1.Text + ".xls";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";
var conn = new OleDbConnection(connectionString);
conn.Open();
var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
var cmd = conn.CreateCommand();
/////////////////////// sheet 1
cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
var adapter = new OleDbDataAdapter(cmd);
var ds = new DataSet();
adapter.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
}