【问题标题】:Cannot create excel file using Microsoft.Jet.OLEDB.4.0无法使用 Microsoft.Jet.OLEDB.4.0 创建 excel 文件
【发布时间】:2014-08-27 16:26:10
【问题描述】:

我在几个来源中找到了如何处理 excel 文件,例如

但是当我尝试使用建议的代码时,我在 OleDbConnection 的命令 Open() 上遇到错误。


System.Data.OleDb.OleDbException:Microsoft Jet 数据库引擎找不到对象“D:\Import2013\Imported\254\template.xls”。 确保对象存在并且拼写它的名称和路径 正确命名。


这是我使用的代码。

string subFolder = Session["LoginID"] != null ? Server.MapPath( "Imported" ) + "\\" + Convert.ToString( Session["LoginID"] ) : "";
if (string.IsNullOrWhiteSpace( subFolder ))
{
    Response.Redirect( "Default.aspx" );
    Response.End();
}
StringBuilder commandText = new StringBuilder( "CREATE TABLE [Imported] (" );
if (!Directory.Exists( subFolder ))
    Directory.CreateDirectory( subFolder );
string fileName = subFolder + "\\template.xls";
if (File.Exists( fileName ))
    File.Delete( fileName );
var connectionString = string.Format( "Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=\"Excel 8.0;HDR=YES;Mode=Write;IMEX=1\"", fileName );
using (var connection = new OleDbConnection( connectionString ))
{
    for (int i = 0; i < lvFieldNames.Count; i++)
    {
        commandText.Append( "[" + lvFieldNames[i].FieldName + "] varchar(64)" );
        if (i < lvFieldNames.Count - 1)
            commandText.Append( ", " );
    }
    commandText.Append( ");" );
    using (var cmd = new OleDbCommand( commandText.ToString(), connection ))
    {
        if (connection.State != System.Data.ConnectionState.Open)
            connection.Open(); //I have got an error on this line
        cmd.ExecuteNonQuery();
    }
    connection.Close();
}

请解释一下我做错了什么。

【问题讨论】:

  • 这是一个罐子射击....如果你安装了这个microsoft.com/en-us/download/details.aspx?id=13255的x64版本尝试安装32位版本
  • @Mick Jet.OleDb.4.0 仅存在于 32 位版本中,如果程序编译为 64 位,错误会有所不同。
  • 你能打开那个文件夹中的现有文件 xls 吗?
  • @Steve,是的,我在这个文件夹中打开和读取 excel 文件没有问题。
  • 另外,我尝试使用代码 File.Create(fileName);检查我是否有权在该文件夹中创建文件,并且文件已创建。

标签: c# asp.net excel oledb


【解决方案1】:

在连接字符串中使用 IMEX=1 会将 Excel 文件置于只读模式。

See ConnectionStrings.com

"IMEX=1;"告诉驱动程序始终读取“混合”(数字, 日期,字符串等)数据列作为文本。 请注意,此选项可能 影响 Excel 工作表写访问负面

要创建 Excel 文件,您需要 IMEX=0 或 IMEX=2

【讨论】:

  • 我只在扩展属性中留下了“Excel 8.0”,它现在可以根据需要工作。对于阅读,我也只使用了“Excel 8.0”,但是在阅读了上面的文章之后,我迷失了方向。非常感谢大家的帮助。
  • 我建议你试试LinqPAD。您可以在该编辑器中编写 sn-ps 代码并立即尝试。这个工具对解决这些令人困惑的情况有很大帮助。
  • 谢谢你,史蒂夫。我会在空闲时间看看它。
猜你喜欢
  • 1970-01-01
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多