I am trying to import an excel file using asp.net and C#. I found an example in VB, but it is using something called "Server.MapPath" which is not resolving to a namespace. I am on .NET 4.0, C#, and windows XP. I found a "HttpServerUtility.MapPath", but I don't know if this is the equivalent for IIS7?
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 Sample
Protected Function ExcelConnection() As 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
End Function