C# 无法使用Microsoft.Jet.OLEDB.4.0创建excel文件

C# 无法使用Microsoft.Jet.OLEDB.4.0创建excel文件,c#,asp.net,excel,oledb,C#,Asp.net,Excel,Oledb,例如,我在几个源代码中找到了如何创建excel文件 但当我尝试使用建议的代码时,我在OleDbConnection的命令Open()上遇到了一个错误 System.Data.OleDb.OLEDBEException:Microsoft Jet数据库引擎找不到对象“D:\Import2013\Imported\254\template.xls”。 确保对象存在,并拼写其名称和路径 正确命名 这是我使用的代码 string subFolder = Session["LoginID"]

例如,我在几个源代码中找到了如何创建excel文件

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


System.Data.OleDb.OLEDBEException: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();
}
string子文件夹=会话[“LoginID”]!=无效的Server.MapPath(“导入的”)+“\\”+Convert.ToString(会话[“LoginID”]):“”;
if(string.IsNullOrWhiteSpace(子文件夹))
{
重定向(“Default.aspx”);
Response.End();
}
StringBuilder commandText=新建StringBuilder(“创建表[导入](”);
如果(!Directory.Exists(子文件夹))
Directory.CreateDirectory(子文件夹);
字符串文件名=子文件夹+“\\template.xls”;
if(File.Exists(fileName))
删除(文件名);
var connectionString=string.Format(“Provider=Microsoft.Jet.OLEDB.4.0;数据源={0};扩展属性=\”Excel 8.0;HDR=YES;Mode=Write;IMEX=1\”,文件名);
使用(var连接=新的OLEDB连接(connectionString))
{
for(int i=0;i

请解释我做错了什么。

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

“IMEX=1;”告诉驾驶员始终读取“混合”(数字, 日期、字符串等)数据列作为文本请注意,此选项可能会 影响excel工作表写入访问权限负数


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

这是一个简单的例子。。。。如果已安装此版本的x64,请尝试安装32位version@MickJet.OleDb.4.0仅存在于32位版本中,如果程序编译为64位,则错误将不同。您是否能够仅打开该文件夹中的现有文件xls?@Steve,是,我在打开和读取此文件夹中的excel文件方面没有问题。此外,我尝试使用code File.Create(fileName);检查我是否有权在该文件夹中创建文件,并且文件已创建。我只在扩展属性“Excel 8.0”中保留了该文件,它现在可以根据需要工作。在阅读方面,我也只使用了“Excel8.0”,但读完上面的文章后,我迷失了方向。非常感谢你们的帮助。我建议你们试试。您可以在该编辑器中编写代码片段,然后立即进行尝试。这个工具对解决这些令人困惑的问题很有帮助。谢谢你,史蒂夫。我会在空闲时间看的。