asp.net从excel导入数据
注意,导入的文件必须在服务器上,因此必须先上传文件到服务器然后再导入。
/// <summary>
/// 导入数据到数据集中
/// </summary>
/// <param name="Path"></param>
/// <param name="TableName"></param>
/// <param name="tablename2">如果这个有就以他为表名,没有的话就以TableName</param>
/// <returns></returns>
public DataTable InputExcel(string Path,string TableName,string tablename2)
{
try
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
if (tablename2.Length > 0 && !tablename2.Equals(string.Empty))
TableName = tablename2;
strExcel = "select * from [" + TableName + "$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
DataTable dt = new DataTable();
myCommand.Fill(dt);
conn.Close();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// 导入数据到数据集中
/// </summary>
/// <param name="Path"></param>
/// <param name="TableName"></param>
/// <param name="tablename2">如果这个有就以他为表名,没有的话就以TableName</param>
/// <returns></returns>
public DataTable InputExcel(string Path,string TableName,string tablename2)
{
try
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
if (tablename2.Length > 0 && !tablename2.Equals(string.Empty))
TableName = tablename2;
strExcel = "select * from [" + TableName + "$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
DataTable dt = new DataTable();
myCommand.Fill(dt);
conn.Close();
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}