DataTable dt = new DataTable();//全局
//第一步:首先上传到服务器
string strFileNewName =DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
FileUpload1.SaveAs(Server.MapPath("../Excel/Upload/" + strFileNewName));
//第二步:将Excel的内容导入到DataTable中
using (OleDbConnection conn = new OleDbConnection("Provider = Microsoft.Ace.OleDb.12.0; Data Source =" + Server.MapPath("../Excel/Upload/" + strFileNewName) + " Extended Properties=Excel 8.0″"))
{
string filepath = Server.MapPath("../Excel/Upload/" + strFileNewName);
bind(filepath);
}
循环表
for (int i = 0; i < dt.Rows.Count; i++)
{对取到的值进行处理}
private void bind(string fileName) {
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" +
"Data Source=" + fileName + ";" +
"Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception err)
{
// MessageBox.Show("操作失败!"+err.ToString());
}
}