asp.net導入excel


//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的數據,根據需要進行操作
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM