打开ExcelConnection C#VS2005时出错

我想导入一个.csv文件到我的数据库。 我可以导入一个Excel工作表到我的数据库,但是由于.csv和.xls文件格式不同,我需要为.csv创build一个导入函数。

以下是我的代码:

protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { // Get the name of the Excel spreadsheet to upload. string strFileName = Server.HtmlEncode(FileUpload1.FileName); // Get the extension of the Excel spreadsheet. string strExtension = Path.GetExtension(strFileName); // Validate the file extension. if (strExtension != ".xls" && strExtension != ".xlsx" && strExtension != ".csv" && strExtension != ".csv") { Response.Write("<script>alert('Failed to import DEM Conflicting Role Datasheet. Cause: Invalid Excel file.');</script>"); return; } // Generate the file name to save. string strUploadFileName = @"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension; // Save the Excel spreadsheet on server. FileUpload1.SaveAs(strUploadFileName); // Create Connection to Excel Workbook string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strUploadFileName + ";Extended Properties=Text;"; using (OleDbConnection ExcelConnection = new OleDbConnection(connStr)){ OleDbCommand ExcelCommand = new OleDbCommand("SELECT [columns] FROM +userrolelist", ExcelConnection); OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand); ExcelConnection.Open(); using (DbDataReader dr = ExcelCommand.ExecuteReader()) { // SQL Server Connection String string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<DB>;User ID=<userid>;Password=<password>"; // Bulk Copy to SQL Server using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString)) { bulkCopy.DestinationTableName = "DEMUserRoles"; bulkCopy.WriteToServer(dr); Response.Write("<script>alert('DEM User Data imported');</script>"); } } } } else Response.Write("<script>alert('Failed to import DEM User Roles Data. Cause: No file found.');</script>"); 

}

该文件已被成功保存,但错误显示该文件的path无效,即使该文件已成功保存为.csv,因此我无法继续将数据导入到数据库的过程。

以下是我的错误截图: 在这里输入图像说明在这里输入图像说明

总之,我有一个错误,即保存csv文件的文件path无效,虽然csv文件已成功保存。 需要一些有经验的帮助。 谢谢

连接string数据源应该只包含CSV文件的path 。 它不应该包含CSV文件的名称。

文件名在SQL语句中被指定为一个表格。

 string dir = @"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\"; string mycsv = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension; string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";Extended Properties=Text;"; OleDbCommand ExcelCommand = new OleDbCommand( "SELECT [columns] FROM " + mycsv, ExcelConnection); 

我强烈build议您不要使用OLE访问Excel文档。 有无数的故障和错误。 一般来说,当一列的不同单元格可以包含不同的数据types时,使用sql来访问数据是无稽之谈。 但即使没有这个,也有足够的错误。

使用COM对象的Excel。 否则,你会在地板上难以相信我:-)