【问题标题】:can not open excel file in c# for different format extension error无法在 c# 中打开 excel 文件以获取不同格式的扩展名错误
【发布时间】:2013-04-15 05:49:07
【问题描述】:

无法在 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];
        }

【问题讨论】:

标签: c# .net excel


【解决方案1】:

这是因为该文件实际上只是一个带有 XLS 扩展名的 CSV 文件,以便在 Excel 中打开它。

它发生在新版本的 Excel 中。年长的会很乐意将它们导出。

有关详细信息,请参阅此 Microsoft 文档:

http://support.microsoft.com/kb/948615

一种选择是简单地将文件名重命名为 .csv,并保持用户界面说它是一个 Excel 文件(Excel 很乐意读取 csv 文件)。鉴于 Windows 倾向于隐藏文件扩展名,这似乎是一个相当有吸引力的选择。

编辑

“外部表不是预期的格式。”通常在尝试使用带有以下连接字符串的 Excel 2007 文件时发生:Microsoft.Jet.OLEDB.4.0 和 Extended Properties=Excel 8.0

通过:

Excel "External table is not in the expected format."

希望对您有所帮助。

【讨论】:

  • 当 C# 想要打开我的 excel 文件时:外部表不是预期的格式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 2023-01-19
  • 2022-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多