2010-09-03 78 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与文件系统之间的开箱即用映射支持,复杂的虚拟目录映射它为你处理)与添加功能,如果你开始一个波形~然后它认为是相对于应用程序根)。

它可能会失败,既不相对于应用程序根目录(始于~)或站点根目录(与/开始),如果你做了沿途的一些重映射是价值观,而是沿着如果你已经做了一些重新映射不管怎样,这可能不是你关心的事情。