【发布时间】:2014-08-27 16:26:10
【问题描述】:
我在几个来源中找到了如何处理 excel 文件,例如
- http://www.codeproject.com/Articles/37055/Working-with-MS-Excel-xls-xlsx-Using-MDAC-and-Oled#create
- Cant create Excel file using OLEDB C#
- http://bytes.com/topic/net/answers/608150-generate-excel-file-without-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);检查我是否有权在该文件夹中创建文件,并且文件已创建。