Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
們可以使用數據綁定(Data Binding)來完成帶可選項的列表,這些可選項來自某個導入的數據源,比如數據庫、XML 文件或者腳本。
數據綁定
下面的控件是支持數據綁定的列表控件:
asp:RadioButtonList
asp:CheckBoxList
asp:DropDownList
asp:Listbox
以上每個控件的可選項通常是在一個或者多個 asp:ListItem 控件中定義,如下:
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="countrylist" runat="server">
<asp:ListItem value="N" text="Norway" />
<asp:ListItem value="S" text="Sweden" />
<asp:ListItem value="F" text="France" />
<asp:ListItem value="I" text="Italy" />
</asp:RadioButtonList>
</form>
</body>
</html>
然而,我們可以使用某種獨立的數據源進行數據綁定,比如數據庫、XML 文件或者腳本,通過數據綁定來填充列表的可選項。
通過使用導入的數據源,數據從 HTML 中分離出來,并且對可選項的修改都是在獨立的數據源中完成的。
在下面的三個章節中,我們將描述如何從腳本化的數據源中綁定數據。
一篇我們學習了如何使用zTree對靜態數據進行綁定并顯示。但是實際運用中數據都是數據庫或者經過計算后得到的,所以這一次我們將上次的Demo改為動態綁定。
數據表如下,其中平pId為0的是根節點
上一次講過zTree的回調事件中可以有許多函數,那么我們就利用點擊節點的回調函數進行動態綁定。但是問題來了,首次加載時網頁上并沒有節點,那么我們如何實現點擊節點加載數據呢?思路是這樣的,首次加載時用ajax向后臺發送一個空請求,點擊節點時ajax發送點擊節點的id。后臺收到請求,將請求參數取出,傳入數據庫查詢方法,此時進行判斷,若參數為空說明是首次加載,則執行的sql語句是select * from demo where pId='0' 即取出根節點,然后返回,而參數不為空則說明是點擊節點發出的請求,此時sql語句是select * from demo where pId='"+id+"'" 即取出父節點是我們點擊節點的節點。
下面上代碼
額,先看效果圖吧
前臺
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="css/metroStyle.css" type="text/css">
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/jquery.ztree.core.js"></script>
</head>
<body align="center" >
<div id="demotree" style="margin-left:230px;margin-top:50px">
<ul id="treeDemo" class="ztree"></ul>
</div>
</body>
<script type="text/javascript">
var treeNodes;
var setting = {
//外觀
view: {
showIcon: true, //設置是否顯示節點圖標
showLine: true, //設置是否顯示節點與節點之間的連線
showTitle: true, //設置是否顯示節點的title提示信息
fontCss : {color:"black",size:30}
},
//異步
async:{
enable: true,//true代表異步
url: "/Demo/DataProcessing",//異步獲取數據的地址
autoParam: ["id=id"]//傳遞id
},
//數據類型
data: {
simpleData: {
enable: true, //設置是否啟用簡單數據格式(json格式)
idKey: "id", //設置啟用簡單數據格式時id對應的屬性名稱(對應json數據中的key)
pidKey: "pId" //設置啟用簡單數據格式時parentId對應的屬性名稱,ztree根據id及pid層級關系構建樹結構
}
},
//回調事件
callback: {
//點擊節點事件
onClick: function(event, treeId, treeNode, clickFlag) {
// 判斷是否父節點 ,是父節點則ajax向后臺發送節點名稱以獲取子文件
if(treeNode.isParent){
//判斷節點是否折疊,若已折疊則請求子節點的數據,返回后展開
if(treeNode.collapse==true){
//ajax提交請求
$.ajax({
url: "/Demo/DataProcessing",//請求的action路徑
type:"post", //提交方式
async:false,//同步
dataType:"json",//數據格式是json
data:{'id':treeNode.id}, //傳遞被點擊節點的id
error: function(){//請求失敗后執行的事件
},
//請求成功后執行事件
success:function(data)
{
var jsondata= data;
//json為空說明沒有子節點,不用執行操作
if(jsondata == null || jsondata == ""){ }
//否則子節點添加到父節點
else{
var treeObj = $.fn.zTree.getZTreeObj("demotree");
var parentZNode = treeObj.getNodeByParam("name",treeNode.name, null);//獲取指定父節點
newNode = treeObj.addNodes(parentZNode,jsondata, false);
}
}
});
}
}
}
}
};
//首次加載用ajax請求初始化
$(function(){
$.ajax({
async : false,
cache:false,
type: 'POST',
dataType : "json",
url: "/Demo/DataProcessing",//請求的action路徑
error: function () {//請求失敗處理函數
alert('請求失敗');
},
success:function(data){ //請求成功后處理函數。
treeNodes = data; //把后臺封裝好的簡單Json格式賦給treeNodes
}
});
});
var zTree;
$(document).ready(function(){
$.fn.zTree.init($("#treeDemo"), setting, treeNodes);
});
</script>
</html>
后臺servlet
package myServlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Db.DbOperate;
import Model.Demo;
import com.alibaba.fastjson.JSON;
/**
* Servlet implementation class DataProcessing
*/
@WebServlet("/DataProcessing")
public class DataProcessing extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DataProcessing() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id=request.getParameter("id");
List<Demo> list;
try {
list = new DbOperate().getDemo(id);
String jsonArr = JSON.toJSONString(list);
System.out.println(jsonArr);
//response.setContentType("application/json; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(jsonArr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
數據庫查詢
package Db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import Model.Demo;
public class DbOperate {
private static String url = "jdbc:mysql://localhost:3306/dir?rewriteBatchedStatements=true";
private static String user = "root";
private static String password = "";
public List<Demo> getDemo(String id) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
System.out.print("!!!!!!!!!");
Connection conn = DriverManager.getConnection(url, user, password);
List<Demo> list = new ArrayList<Demo>();
Statement s = null;
String sql;
if(id==null||id==""){
sql= "select * from demo where pId='0'";
}
else{
sql= "select * from demo where pId='"+id+"'";
}
s = conn.createStatement();
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
list.add(new Demo(rs.getString("id"), rs.getString("name"), rs.getString("pId"), rs.getInt("isParent")));
}
if (s != null) {
s.close();
}
if (conn != null) {
conn.close();
}
return list;
}
}
實體類
package Model;
public class Demo {
private String id;
private String name;
private String pId;
private int isParent;
public Demo(String id, String name, String pId, int isParent) {
super();
this.id = id;
this.name = name;
this.pId = pId;
this.isParent = isParent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getpId() {
return pId;
}
public void setpId(String pId) {
this.pId = pId;
}
public int getIsParent() {
return isParent;
}
public void setIsParent(int isParent) {
this.isParent = isParent;
}
}
源碼可以私信獲取,謝謝支持
臺拖一個Gridview,在拖一個導出excel的按鈕,給這個按鈕添加事件
后臺代碼:
using BLL;
using Model;
namespace Web
{
public partial class ExcelOperate : System.Web.UI.Page
{
private StudentBLL bll = new StudentBLL();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
//綁定數據
private void Bind()
{
GridView1.DataSource = bll.GetAllStu(null);
GridView1.DataBind();
}
#region 導出到excel
//導出excel
protected void btnExcelout_Click(object sender, EventArgs e)
{
string style = @"<style> .text { mso-number-format:\@; } </script> "; //設置格式
Response.ClearContent();
Response.ContentEncoding = Encoding.GetEncoding("gbk");
Response.AddHeader("content-disposition", "attachment;filename=ouput.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(style);//注意
Response.Write(sw.ToString());
Response.End();
}
//注意:必須覆蓋此方法
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
//解決數字字符串顯示不完全
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// e.Row.Cells[3].Attributes.Add("class", "text");//在數據綁定中設置格式
//哪一列需要顯示文本的,加上下面這句話即可
e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
#endregion
}
}
頁面效果:
導入Excel并保存到數據庫:
前臺需要拖一個FileUpload上傳控件,一個導入excel按鈕,給其添加事件:
//導入excel數據
protected void btnExcelIn_Click(object sender, EventArgs e)
{
string filepath = string.Empty;
string getErrormg = string.Empty;
DataTable dt=new DataTable();
if (!fuFile.HasFile)
{
Response.Write("<script>alert('請選擇你要導入的Excel文件');</script>");
return;
}
//獲取文件的后綴名
string fileExt = System.IO.Path.GetExtension(fuFile.FileName);
if (fileExt != ".xls")
{
Response.Write("<script>alert('文件類型錯誤!');</script>");
return;
}
//獲取絕對路徑
filepath = fuFile.PostedFile.FileName;
string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";Data Source=" + filepath;
OleDbConnection excelCon = new OleDbConnection(conn);
//Excel文件里面工作表名 默認為Sheet1,后面需要加上$符號[工作表名稱$]切記,不然會報錯
OleDbDataAdapter odda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", excelCon);
try
{
odda.Fill(dt);
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write("<script>alert('" + ex.Message + "!')</script>");
}
finally
{
excelCon.Close();
excelCon.Dispose();
}
//將數據寫到數據庫里面
try
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Studnet stu=new Studnet();
stu.C_id = Convert.ToInt32(dt.Rows[i]["c_id"]);
stu.No = dt.Rows[i]["no"].ToString();
stu.Name = dt.Rows[i]["name"].ToString();
stu.Gender = dt.Rows[i]["gender"].ToString() == "男" ? true : false;
stu.Age = Convert.ToInt32(dt.Rows[i]["age"].ToString());
bll.InsertStu(stu);
}
}
catch (Exception ex)
{
getErrormg = ex.Message;
Response.Write(ex.Message);
}
if (getErrormg == "")
{
Response.Write("<script>alert('導入Excel文件成功!')</script>");
Bind();
}
else { Response.Write("<script>alert('導入Excel文件失敗!')</script>"); }
}
Excel和導入后的頁面效果:
數據庫在導入excel數據之前和時候的效果:
這里要注意幾個地方,一般導出excel的時候,數字文本會把前面的0都省略掉了,這里需要注意:紅色代碼片段,導入的時候,也有個***紅紅紅色***標記碼塊要注意
以下是前臺完整代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExcelOperate.aspx.cs" Inherits="Web.ExcelOperate" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"></asp:GridView>
<br />
<asp:Button ID="btnExcelout" runat="server" OnClick="btnExcelout_Click" Text="導出到Excel" />
<br />
<asp:FileUpload ID="fuFile" runat="server" />
<asp:Button ID="btnExcelIn" runat="server" OnClick="btnExcelIn_Click" Text="導入Excel數據" />
</div>
</form>
</body>
</html>
以下是后臺完整代碼:
*請認真填寫需求信息,我們會在24小時內與您取得聯系。