2011-11-01 210 views
0

我遇到了错误:多步OLE DB操作产生错误。检查每个OLE DB状态值(如果可用)。没有工作完成。我正在使用SQL Server 2005和Visual Studio 2005.C#导入excel文件到sql数据库错误

我在将excel文件导入到我的sql表中的一个表中时遇到了此错误。以下是我的代码:

#region Using directives 
using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Data.OleDb; 
using System.Data.SqlClient; 
using System.IO; 
using System.Configuration; 
#endregion Using directives 

namespace CSASPNETExcelImportExport 
{ 
public partial class ExcelImport : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 

    // Get the row counts in SQL Server table. 
    protected int GetRowCounts() 
    { 
     int iRowCount = 0; 

     using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=<IP>;Initial Catalog=SOD;Persist Security Info=True;User ID=<username>;Password=<password>"].ToString())) 
     { 
      SqlCommand cmd = new SqlCommand("select count(*) from <database>", conn); 
      conn.Open(); 

      // Execute the SqlCommand and get the row counts. 
      iRowCount = (int)cmd.ExecuteScalar(); 
     } 

     return iRowCount; 
    } 

    // Retrieve data from the Excel spreadsheet. 
    protected DataTable RetrieveData(string strConn) 
    { 
     DataTable dtExcel = new DataTable(); 

     using (OleDbConnection conn = new OleDbConnection(strConn)) 
     { 
      // Initialize an OleDbDataAdapter object. 
      OleDbDataAdapter da = new OleDbDataAdapter("select * from <database>", conn); 

      // Fill the DataTable with data from the Excel spreadsheet. 
      da.Fill(dtExcel); 
     } 

     return dtExcel; 
    } 

    // Import the data from DataTable to SQL Server via SqlBulkCopy 
    protected void SqlBulkCopyImport(DataTable dtExcel) 
    { 
     using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=<ip>;Initial Catalog=SOD;Persist Security Info=True;User ID=<username>;Password=<password>"].ToString())) 
     { 
      // Open the connection. 
      conn.Open(); 

      using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn)) 
      { 
       // Specify the destination table name. 
       bulkCopy.DestinationTableName = "<database>"; 

       foreach (DataColumn dc in dtExcel.Columns) 
       { 
        // Because the number of the test Excel columns is not 
        // equal to the number of table columns, we need to map 
        // columns. 
        bulkCopy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName); 
       } 

       // Write from the source to the destination. 
       bulkCopy.WriteToServer(dtExcel); 
      } 
     } 
    } 

    protected void btnImport_Click(object sender, EventArgs e) 
    { 
     // Before attempting to import the file, verify 
     // that the FileUpload control contains a file. 
     if (fupExcel.HasFile) 
     { 
      // Get the name of the Excel spreadsheet to upload. 
      string strFileName = Server.HtmlEncode(fupExcel.FileName); 

      // Get the extension of the Excel spreadsheet. 
      string strExtension = Path.GetExtension(strFileName); 

      // Validate the file extension. 
      if (strExtension != ".xls" && strExtension != ".xlsx") 
      { 
       Response.Write("<script>alert('Please select a Excel spreadsheet to import!');</script>"); 
       return; 
      } 

      // Generate the file name to save. 
      string strUploadFileName = "~/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension; 

      // Save the Excel spreadsheet on server. 
      fupExcel.SaveAs(Server.MapPath(strUploadFileName)); 

      // Generate the connection string for Excel file. 
      string strExcelConn = ""; 

      // There is no column name In a Excel spreadsheet. 
      // So we specify "HDR=YES" in the connection string to use 
      // the values in the first row as column names. 
      if (strExtension == ".xls") 
      { 
       // Excel 97-2003 
       strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\""; 

       //if the above doesn't work, you may need to prefix OLEDB; to the string, e.g. 
       //strExcelConn = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<URL>" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\""; 
      } 
      else 
      { 
       // Excel 2007 
       strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<URL>" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\""; 
      } 

      DataTable dtExcel = RetrieveData(strExcelConn); 

      // Get the row counts before importing. 
      int iStartCount = GetRowCounts(); 

      // Import the data. 
      SqlBulkCopyImport(dtExcel); 

      // Get the row counts after importing. 
      int iEndCount = GetRowCounts(); 

      // Display the number of imported rows. 
      lblMessages.Text = Convert.ToString(iEndCount - iStartCount) + " rows were imported into Person table"; 

      if (rblArchive.SelectedValue == "No") 
      { 
       // Remove the uploaded Excel spreadsheet from server. 
       File.Delete(Server.MapPath(strUploadFileName)); 
      } 
     } 
    } 
} 
} 

是因为我的连接字符串错误?


我改变了我的连接字符串,作为Nathan的建议。现在我遇到了以下错误:

http://i.stack.imgur.com/nWyte.png

http://i.stack.imgur.com/nWyte.png

这个时候有什么错误呢? D:

+1

这是重现错误所需的_minimum_数量的代码? –

回答

1

它看起来像你确实有几件事情错了你的连接字符串。首先,Excel连接字符串不应包含“初始目录”,并且它们应包含引用该文件的数据源,而不是服务器。

试试这个:

 // There is no column name In a Excel spreadsheet. 
     // So we specify "HDR=YES" in the connection string to use 
     // the values in the first row as column names. 
     if (strExtension == ".xls") 
     { 
      // Excel 97-2003 
      strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\""; 

      //if the above doesn't work, you may need to prefix OLEDB; to the string, e.g. 
      //strExcelConn = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\""; 
     } 
     else 
     { 
      // Excel 2007 
      strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\""; 
     } 

据透露,http://connectionstrings.com是这类事情的好资源。