EXCEL转换为DATATABLE #region EXCEL转换为DATATABLE
/**//// <summary>
/// 读取Excel文档
/// </summary>
/// <param name="Path">文件路径</param>
/// <returns>返回一个数据集</returns>
public DataTable ExcelToDS(string Path, string name)
...{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel = "select * from [" + name + "$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, "table1");
DataTable dt = ds.Tables["table1"];
return dt;
}
#endregion
上传 #region 上传
protected void upbtn_ServerClick(object sender, EventArgs e)
...{
if (hidstr.Value.Length > 0)
...{
try
...{
//上传文件,获取上传文件的服务器路径。
HttpFileCollection files = HttpContext.Current.Request.Files;
HttpPostedFile pstfile = files[0];
string fileName = System.IO.Path.GetFileName(pstfile.FileName);//文件名
string fileExtension = System.IO.Path.GetExtension(hidstr.Value);//扩展名
fileName = fileName.Substring(0, fileName.Length - fileExtension.Length);
string filepath = "../temp/";
string fpath = Server.MapPath(filepath + fileName + fileExtension);
pstfile.SaveAs(Server.MapPath(filepath + fileName + fileExtension));
string name = GetExName(fpath);
DataTable dt = ExcelToDS(fpath, name);
InsertTo(dt);//插入数据库
File.Delete(fpath);//刪除文件
Page.RegisterStartupScript("", "<script>alert('上傳成功!');</script>");
}
catch (Exception ex)
...{
Page.RegisterStartupScript("", "<script>alert('上傳失敗,請檢察文件格式!');</script>");
throw new ApplicationException(ex.Message, ex);
}
}
}
#endregion