无法使用Microsoft.Jet.OLEDB.4.0创buildexcel文件

例如,我发现在几个来源如何ctreate excel文件

  • http://www.codeproject.com/Articles/37055/Working-with-MS-Excel-xls-xlsx-Using-MDAC-and-Oled#create
  • 无法使用OLEDB创buildExcel文件C#
  • http://bytes.com/topic/net/answers/608150-generate-excel-file-without-excel

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


System.Data.OleDb.OleDbException:Microsoft Jet数据库引擎找不到对象'D:\ Import2013 \ Imported \ 254 \ template.xls'。 确保对象存在,并且正确拼写其名称和path名称。


这是我使用的代码。

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中使用IMEX = 1将Excel文件置于只读模式。

请参阅ConnectionStrings.com

“IMEX = 1;” 告诉驱动程序总是读取“混合”(数字,date,string等)数据列作为文本。 请注意,这个选项可能会影响Excel表单写访问的负面影响

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