//FileUpload1是asp.net里文件上传控件的id,加在前台页面
if (!fileUploadExcel.HasFile)
{
Response.Write("<script>alert('Please select the excel file to import.');</script>");
return;
}
//获取文件的后缀名
string fileExt = System.IO.Path.GetExtension(fileUploadExcel.FileName);
if (fileExt == ".xls" || fileExt == ".xlsx")
{ }
else
{
Response.Write("<script>alert('File type is invalid.');</script>");
return;
}
//这里后面要适配xlsx
//fileUploadExcel.SaveAs(Server.MapPath("~/" + System.IO.Path.GetFileName(fileUploadExcel.PostedFile.FileName)));
string fileName = fileUploadExcel.PostedFile.FileName;
fileUploadExcel.SaveAs(Server.MapPath("~/" + System.IO.Path.GetFileName(fileName)));
string connstring = "";
if (fileExt == ".xls")
{
//这个适配语句是适合excel2007版本以下的
connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";Data Source=" + Server.MapPath("~/" + System.IO.Path.GetFileName(fileName));
}
else
{
//下面这个是针对2007及以上的
connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/" + System.IO.Path.GetFileName(fileName)) + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=0';";
}
DataSet ds = new DataSet();
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
DataTable sheetsNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//得到所有sheet的名字
string firstSheetName = sheetsNames.Rows[0][2].ToString();
//得到第一个sheet的名字
string sql = string.Format("SELECT * FROM [{0}]", firstSheetName);
OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
ada.Fill(ds);
//ds数据就是导入excel的数据,根据需要进行操作
}
}