2011-03-02 42 views
0

我已經能夠在本地導入excel文件sql bulkcopy。但是,當我將代碼發佈到服務器時,出現以下錯誤消息:使用bulkcopy將excel文件導入到sql

異常消息:'C:\ MyTest.xls'不是有效的路徑。確保路徑名拼寫正確,並且您已連接到文件所在的服務器。

異常源:Microsoft Jet數據庫引擎

這裏是代碼:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" %> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <asp:FileUpload ID="txtFile" runat="server" /> 
     <br /><br /> 
     <asp:Button ID="Button1" runat="server" Text="Button" /> 
    </form> 
</body> 
</html> 


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click 

    Dim excelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & txtFile.PostedFile.FileName & ";Extended Properties=""Excel 8.0;HDR=YES;""" 

    Using connection As New System.Data.OleDb.OleDbConnection(excelConnectionString) 
     'List columns you need from the Excel file 
     Dim command As New System.Data.OleDb.OleDbCommand("Select [Name],[Location] FROM [Sheet1$]", connection) 
     connection.Open() 

     ' Create DbDataReader to Data Worksheet 
     Using dr As System.Data.OleDb.OleDbDataReader = command.ExecuteReader() 
      ' SQL Server Connection String 
      Dim con As SqlConnection = GetConnection() 

      Using bulkCopy As New System.Data.SqlClient.SqlBulkCopy(con) 
       bulkCopy.DestinationTableName = "tblExcel" 

       'Define ColumnMappings: source(Excel) --destination(DB Table column) 
       bulkCopy.ColumnMappings.Add("Name", "Name") 
       bulkCopy.ColumnMappings.Add("Location", "Location") 
       bulkCopy.WriteToServer(dr) 
      End Using 

      CloseConnection(con) 

     End Using 

    End Using 

End Sub 

回答

0

你應該首先將文件保存(另存爲(路徑),使用向使用Server.Mappath映射相對目錄),然後給出連接字符串的完整路徑。

+0

你能提供一點點細節。這對我來說是完全新的嘗試導入一個Excel文件。謝謝 – Mike 2011-03-02 18:13:18

+1

查看http://msdn.microsoft.com/en-us/library/ysf0192b.aspx您需要將文件保存到預定義的路徑並在連接字符串中使用該路徑。 – 2011-03-02 18:50:44