2010-09-03 86 views
1

我想用asp.net和C#導入一個excel文件。我在VB中找到了一個例子,但它使用了一種名爲「Server.MapPath」的東西,它不能解析爲名稱空間。我在.NET 4.0,C#和Windows XP上。我發現了一個「HttpServerUtility.MapPath」,但我不知道這是否與IIS7等效?在ASP.NET中上傳文件

C#

public OleDbCommand ExcelConnection()   
{       
    string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/ExcelImport.xls") + ";" + "Extended Properties=Excel 8.0;"; 
    //create your excel connection object using the connection string 
    OleDbConnection ocnct = new OleDbConnection(conStr); 
    ocnct.Open(); 

    //use a SQL Select command to retrieve the data from the Excel Spreadsheet 
    //the "table name" is the name of the worksheet within the spreadsheet 
    //in this case, the worksheet name is "Members" and is coded as: [Members$] 
    OleDbCommand ocmd = new OleDbCommand("SELECT * FROM [Members$]", ocnct); 
    return ocmd; 
} 

Online樣品

保護的函數ExcelConnection()作爲的OleDbCommand

' Connect to the Excel Spreadsheet 
Dim xConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
      "Data Source=" & Server.MapPath("~/ExcelImport.xls") & ";" & _ 
      "Extended Properties=Excel 8.0;" 

' create your excel connection object using the connection string 
Dim objXConn As New OleDbConnection(xConnStr) 
objXConn.Open() 

' use a SQL Select command to retrieve the data from the Excel Spreadsheet 
' the "table name" is the name of the worksheet within the spreadsheet 
' in this case, the worksheet name is "Members" and is coded as: [Members$] 
Dim objCommand As New OleDbCommand("SELECT * FROM [Members$]", objXConn) 
Return objCommand 

端功能

回答

1

Server.MapPath需要的應用程序相對路徑(具有開始)並將其轉換爲磁盤上的完整路徑。
它是Server對象(HttpServerUtility類的一個實例)的成員,可以在HttpContext和頁面或用戶控件上找到它。

如果您已經擁有磁盤上的完整路徑,則不需要它。

1

HttpContextPage類都有一個名爲Server屬性,它返回一個HttpServerUtility對象(其實,Page只是調用return this.Context.Server)。因此Server.MapPathHttpServerUtility.MapPath

它接受一個字符串並計算它對應的文件路徑,如果該字符串是一個相對URI,並且由應用程序處理的URI與文件系統之間的開箱即用映射支持,複雜的虛擬目錄映射它爲你處理)與添加功能,如果你開始一個波形~然後它認爲是相對於應用程序根)。

它可能會失敗,既不相對於應用程序根目錄(始於~)或站點根目錄(與/開始),如果你做了沿途的一些重映射是價值觀,而是沿着如果你已經做了一些重新映射不管怎樣,這可能不是你關心的事情。