Spring+Hibernate+Struts2+Ext+Excel导入导出

-------------------------------VO

package com.longtop.demo;

/**
 * Demo entity.
 *
 * @author MyEclipse Persistence Tools
 */
public class Demo extends AbstractDemo implements java.io.Serializable {

 // Constructors

 /** default constructor */
 public Demo() {
 }

 /** minimal constructor */
 public Demo(String id) {
  super(id);
 }

 /** full constructor */
 public Demo(String id, String name, String age, String memo) {
  super(id, name, age, memo);
 }

}
-------------------------------------AbstractVO

package com.longtop.demo;

/**
 * AbstractDemo entity provides the base persistence definition of the Demo
 * entity.
 *
 * @author MyEclipse Persistence Tools
 */

public abstract class AbstractDemo implements java.io.Serializable {

 // Fields

 private String id;
 private String name;
 private String age;
 private String memo;

 // Constructors

 /** default constructor */
 public AbstractDemo() {
 }

 /** minimal constructor */
 public AbstractDemo(String id) {
  this.id = id;
 }

 /** full constructor */
 public AbstractDemo(String id, String name, String age, String memo) {
  this.id = id;
  this.name = name;
  this.age = age;
  this.memo = memo;
 }

 // Property accessors

 public String getId() {
  return this.id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return this.name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAge() {
  return this.age;
 }

 public void setAge(String age) {
  this.age = age;
 }

 public String getMemo() {
  return this.memo;
 }

 public void setMemo(String memo) {
  this.memo = memo;
 }

}

 

----------------------------Action

package com.longtop.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.struts2.ServletActionContext;

import com.longtop.until.DateUtil;
import com.longtop.until.ExtHelper;

public class DemoAction {

 private DemoDAO demodao;

 @SuppressWarnings("unchecked")
 public String listDemo() {
  HttpServletResponse response = ServletActionContext.getResponse();
  HttpServletRequest request = ServletActionContext.getRequest();
  try {
   response.setContentType("text/json;charset=utf-8");
   PrintWriter out = response.getWriter();
   int start = Integer.parseInt(request.getParameter("start"));
   int limit = Integer.parseInt(request.getParameter("limit"));
   int end = limit + start;
   List<Demo> demolist = new ArrayList<Demo>();
   demolist = demodao.findAll(start, end);
   List<Demo> demolist1 = new ArrayList<Demo>();
   demolist1 = demodao.findAll();
   int recordTotal = demolist1.size();
   String newsJson = ExtHelper.getJsonFromList(recordTotal, demolist);
   out.write(newsJson);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 public String insertDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setContentType("text/html;charset=utf-8");
  String name = request.getParameter("name");
  String age = request.getParameter("age");
  String memo = request.getParameter("memo");
  Demo demo = new Demo();
  demo.setName(name);
  demo.setAge(age);
  demo.setMemo(memo);
  try {
   demodao.save(demo);
   response.getWriter().write(
     "{success:" + true + ",demoId:" + demo.getId() + "}");
  } catch (Exception e) {
   e.printStackTrace();
   try {
    response.getWriter().write("{success:false");
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
  }
  return null;
 }

 public String selectDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setContentType("text/html;charset=utf-8");
  try {
   Demo demo = new Demo();
   String id = request.getParameter("demoId");
   demo = demodao.findById(id);
   String json = null;
   if (demo != null) {
    json = "{success:true,data:" + ExtHelper.getJsonFromBean(demo)
      + "}";
   } else {
    json = "{success:false}";
   }
   response.getWriter().write(json);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 public String updateDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setContentType("text/html;charset=utf-8");
  try {
   String name = request.getParameter("name");
   String id = request.getParameter("id");
   String age = request.getParameter("age");
   String memo = request.getParameter("memo");
   Demo demo = new Demo();
   demo.setId(id);
   demo.setName(name);
   demo.setAge(age);
   demo.setMemo(memo);
   demodao.attachDirty(demo);
   response.getWriter().write(
     "{success:true,demoId:" + demo.getId() + "}");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 public String deleteDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setContentType("text/html;charset=utf-8");
  try {
   String id = request.getParameter("demoId");
   int num = 1 ;
   String[] str = id.split("@");
   if(str.length>1){
    for(int i=1;i<str.length;i++){
     Demo demo = new Demo();
     demo.setId(str[i]);
     demodao.delete(demo);
    }
    num = str.length-1;
   }else{
    Demo demo = new Demo();
    demo.setId(id);
    demodao.delete(demo);
   }
   response.getWriter().write("{success:" + true + ",num:" + num  + "}");
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 /*
  * 导出人员信息
  */
 @SuppressWarnings("unchecked")
 public String showExcelDemo() {
  HttpServletResponse response = ServletActionContext.getResponse();
  try {
   List<Demo> demolist = new ArrayList<Demo>();
   demolist = demodao.findAll();
   String filename = "d:\\人员资料_"
     + DateUtil.formatDate().replace("-", "") + ".xls";
   ExcelDemo(filename, demolist);
   response.getWriter().write("{success:" + true + ",num:" + 0 + "}");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 /*
  * 导入人员信息
  */
 @SuppressWarnings("unchecked")
 public String InExcelDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  try {
   // String filePath = request.getParameter("filePath");
   String filePath = "d:\\模板.xls";
   ArrayList list1 = readExcel(filePath);
   List list = new ArrayList<Demo>();
   for (int i = 0; i < list1.size(); i++) {
    List list2 = (List) list1.get(i);
    for (int j = 1; j < list2.size(); j++) {
     List list3 = (List) list2.get(j);
     for (int k = 2; k < list3.size(); k++) {
      List list4 = (List) list3.get(k);
      Demo demo = new Demo();
      demo.setName((String) list4.get(1));
      demo.setAge((String) list4.get(2));
      demo.setMemo((String) list4.get(3));
      if("".equals(list4.get(1))){
       break;
      }
      list.add(demo);
     }
    }
   }
   if(list.size()==0){
    response.getWriter().write("{success:false}");
   }
   else{
    Iterator it = list.iterator();
    while (it.hasNext()) {
     Demo de = (Demo) it.next();
     demodao.save(de);
    }
    response.getWriter().write("{success:" + true + ",num:" + 0 + "}");
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 /*
  * 导出Excel
  */
 public void ExcelDemo(String filePath, List<Demo> ve) {
  WritableWorkbook wwb;
  try {
   wwb = Workbook.createWorkbook(new File(filePath));
   WritableSheet ws = wwb.createSheet("人员资料", 10);
   ws.addCell(new jxl.write.Label(0, 1, "ID"));
   ws.addCell(new jxl.write.Label(1, 1, "姓名"));
   ws.addCell(new jxl.write.Label(2, 1, "年龄"));
   ws.addCell(new jxl.write.Label(3, 1, "描述"));
   int demoSize = ve.size();
   Demo demo = new Demo();
   for (int i = 0; i < demoSize; i++) {
    demo = (Demo) ve.get(i);
    ws.addCell(new jxl.write.Label(0, i + 2, "" + demo.getId()));
    ws.addCell(new jxl.write.Label(1, i + 2, demo.getName()));
    ws.addCell(new jxl.write.Label(2, i + 2, "" + demo.getAge()));
    ws.addCell(new jxl.write.Label(3, i + 2, demo.getMemo()));
   }
   ws.addCell(new jxl.write.Label(0, 0, "最新人员信息"));
   wwb.write();
   // 关闭Excel工作薄对象
   wwb.close();
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 /**
  * 读取Excel中的数据.将这些数据放入到一个三维数组中.
  *
  * @author Administrator
  * @param filePath
  *            文件路径.
  * @deprecated:读取Excel中的数据将它放入到ArrayList数组中(此为三维数组).
  */
 @SuppressWarnings( { "unchecked", "unchecked" })
 public static ArrayList readExcel(String filePath) {
  ArrayList subdata = new ArrayList();
  String tablename = null;
  try {
   subdata.clear();// 将静态ArrayList数组清空.(如果不清空原数据会不断累加)
   InputStream is = new FileInputStream(filePath);
   Workbook rwb = Workbook.getWorkbook(is);
   Sheet st[] = rwb.getSheets();// 得到所有Excel中页的列表.
   for (int a = 0; a < st.length; a++) {
    ArrayList alList = new ArrayList();
    ArrayList tablenames = new ArrayList();
    ArrayList tableAndContents = new ArrayList();
    tablename = st[a].getName().trim();
    int b = 0;
    for (int i = 0; i < st[a].getRows(); i++) {
     ArrayList al = new ArrayList();
     for (int j = 0; j < st[a].getColumns(); j++) {
      Cell c00 = st[a].getCell(j, i);
      // 通用的获取cell值的方式,返回字符串
      String strc00 = c00.getContents().trim();
      // 获得cell具体类型值的方式得到内容.
      al.add(j, strc00);
     }
     alList.add(b, al);
     b++;
    }
    tablenames.add(tablename);
    tableAndContents.add(0, tablenames);
    tableAndContents.add(1, alList);
    subdata.add(a, tableAndContents);
   }
  
   rwb.close();
   is.close();
   // 关闭
  } catch (Exception e) {
   e.printStackTrace();
  }
  return subdata;
 }

 public void setDemodao(DemoDAO demodao) {
  this.demodao = demodao;
 }
}
-------------------------DAO

package com.longtop.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.struts2.ServletActionContext;

import com.longtop.until.DateUtil;
import com.longtop.until.ExtHelper;

public class DemoAction {

 private DemoDAO demodao;

 @SuppressWarnings("unchecked")
 public String listDemo() {
  HttpServletResponse response = ServletActionContext.getResponse();
  HttpServletRequest request = ServletActionContext.getRequest();
  try {
   response.setContentType("text/json;charset=utf-8");
   PrintWriter out = response.getWriter();
   int start = Integer.parseInt(request.getParameter("start"));
   int limit = Integer.parseInt(request.getParameter("limit"));
   int end = limit + start;
   List<Demo> demolist = new ArrayList<Demo>();
   demolist = demodao.findAll(start, end);
   List<Demo> demolist1 = new ArrayList<Demo>();
   demolist1 = demodao.findAll();
   int recordTotal = demolist1.size();
   String newsJson = ExtHelper.getJsonFromList(recordTotal, demolist);
   out.write(newsJson);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 public String insertDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setContentType("text/html;charset=utf-8");
  String name = request.getParameter("name");
  String age = request.getParameter("age");
  String memo = request.getParameter("memo");
  Demo demo = new Demo();
  demo.setName(name);
  demo.setAge(age);
  demo.setMemo(memo);
  try {
   demodao.save(demo);
   response.getWriter().write(
     "{success:" + true + ",demoId:" + demo.getId() + "}");
  } catch (Exception e) {
   e.printStackTrace();
   try {
    response.getWriter().write("{success:false");
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
  }
  return null;
 }

 public String selectDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setContentType("text/html;charset=utf-8");
  try {
   Demo demo = new Demo();
   String id = request.getParameter("demoId");
   demo = demodao.findById(id);
   String json = null;
   if (demo != null) {
    json = "{success:true,data:" + ExtHelper.getJsonFromBean(demo)
      + "}";
   } else {
    json = "{success:false}";
   }
   response.getWriter().write(json);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 public String updateDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setContentType("text/html;charset=utf-8");
  try {
   String name = request.getParameter("name");
   String id = request.getParameter("id");
   String age = request.getParameter("age");
   String memo = request.getParameter("memo");
   Demo demo = new Demo();
   demo.setId(id);
   demo.setName(name);
   demo.setAge(age);
   demo.setMemo(memo);
   demodao.attachDirty(demo);
   response.getWriter().write(
     "{success:true,demoId:" + demo.getId() + "}");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 public String deleteDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setContentType("text/html;charset=utf-8");
  try {
   String id = request.getParameter("demoId");
   int num = 1 ;
   String[] str = id.split("@");
   if(str.length>1){
    for(int i=1;i<str.length;i++){
     Demo demo = new Demo();
     demo.setId(str[i]);
     demodao.delete(demo);
    }
    num = str.length-1;
   }else{
    Demo demo = new Demo();
    demo.setId(id);
    demodao.delete(demo);
   }
   response.getWriter().write("{success:" + true + ",num:" + num  + "}");
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 /*
  * 导出人员信息
  */
 @SuppressWarnings("unchecked")
 public String showExcelDemo() {
  HttpServletResponse response = ServletActionContext.getResponse();
  try {
   List<Demo> demolist = new ArrayList<Demo>();
   demolist = demodao.findAll();
   String filename = "d:\\人员资料_"
     + DateUtil.formatDate().replace("-", "") + ".xls";
   ExcelDemo(filename, demolist);
   response.getWriter().write("{success:" + true + ",num:" + 0 + "}");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 /*
  * 导入人员信息
  */
 @SuppressWarnings("unchecked")
 public String InExcelDemo() {
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  try {
   // String filePath = request.getParameter("filePath");
   String filePath = "d:\\模板.xls";
   ArrayList list1 = readExcel(filePath);
   List list = new ArrayList<Demo>();
   for (int i = 0; i < list1.size(); i++) {
    List list2 = (List) list1.get(i);
    for (int j = 1; j < list2.size(); j++) {
     List list3 = (List) list2.get(j);
     for (int k = 2; k < list3.size(); k++) {
      List list4 = (List) list3.get(k);
      Demo demo = new Demo();
      demo.setName((String) list4.get(1));
      demo.setAge((String) list4.get(2));
      demo.setMemo((String) list4.get(3));
      if("".equals(list4.get(1))){
       break;
      }
      list.add(demo);
     }
    }
   }
   if(list.size()==0){
    response.getWriter().write("{success:false}");
   }
   else{
    Iterator it = list.iterator();
    while (it.hasNext()) {
     Demo de = (Demo) it.next();
     demodao.save(de);
    }
    response.getWriter().write("{success:" + true + ",num:" + 0 + "}");
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

 /*
  * 导出Excel
  */
 public void ExcelDemo(String filePath, List<Demo> ve) {
  WritableWorkbook wwb;
  try {
   wwb = Workbook.createWorkbook(new File(filePath));
   WritableSheet ws = wwb.createSheet("人员资料", 10);
   ws.addCell(new jxl.write.Label(0, 1, "ID"));
   ws.addCell(new jxl.write.Label(1, 1, "姓名"));
   ws.addCell(new jxl.write.Label(2, 1, "年龄"));
   ws.addCell(new jxl.write.Label(3, 1, "描述"));
   int demoSize = ve.size();
   Demo demo = new Demo();
   for (int i = 0; i < demoSize; i++) {
    demo = (Demo) ve.get(i);
    ws.addCell(new jxl.write.Label(0, i + 2, "" + demo.getId()));
    ws.addCell(new jxl.write.Label(1, i + 2, demo.getName()));
    ws.addCell(new jxl.write.Label(2, i + 2, "" + demo.getAge()));
    ws.addCell(new jxl.write.Label(3, i + 2, demo.getMemo()));
   }
   ws.addCell(new jxl.write.Label(0, 0, "最新人员信息"));
   wwb.write();
   // 关闭Excel工作薄对象
   wwb.close();
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 /**
  * 读取Excel中的数据.将这些数据放入到一个三维数组中.
  *
  * @author Administrator
  * @param filePath
  *            文件路径.
  * @deprecated:读取Excel中的数据将它放入到ArrayList数组中(此为三维数组).
  */
 @SuppressWarnings( { "unchecked", "unchecked" })
 public static ArrayList readExcel(String filePath) {
  ArrayList subdata = new ArrayList();
  String tablename = null;
  try {
   subdata.clear();// 将静态ArrayList数组清空.(如果不清空原数据会不断累加)
   InputStream is = new FileInputStream(filePath);
   Workbook rwb = Workbook.getWorkbook(is);
   Sheet st[] = rwb.getSheets();// 得到所有Excel中页的列表.
   for (int a = 0; a < st.length; a++) {
    ArrayList alList = new ArrayList();
    ArrayList tablenames = new ArrayList();
    ArrayList tableAndContents = new ArrayList();
    tablename = st[a].getName().trim();
    int b = 0;
    for (int i = 0; i < st[a].getRows(); i++) {
     ArrayList al = new ArrayList();
     for (int j = 0; j < st[a].getColumns(); j++) {
      Cell c00 = st[a].getCell(j, i);
      // 通用的获取cell值的方式,返回字符串
      String strc00 = c00.getContents().trim();
      // 获得cell具体类型值的方式得到内容.
      al.add(j, strc00);
     }
     alList.add(b, al);
     b++;
    }
    tablenames.add(tablename);
    tableAndContents.add(0, tablenames);
    tableAndContents.add(1, alList);
    subdata.add(a, tableAndContents);
   }
  
   rwb.close();
   is.close();
   // 关闭
  } catch (Exception e) {
   e.printStackTrace();
  }
  return subdata;
 }

 public void setDemodao(DemoDAO demodao) {
  this.demodao = demodao;
 }
}
-----------------------------------------------------------------------------------------applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">


 <bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName"
   value="oracle.jdbc.driver.OracleDriver">
  </property>
  <property name="url"
   value="jdbc:oracle:thin:@127.0.0.1:1521:orcl">
  </property>
  <property name="username" value="scott"></property>
  <property name="password" value="tiger"></property>
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource">
   <ref bean="dataSource" />
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">
     org.hibernate.dialect.OracleDialect
    </prop>
    <prop key="hibernate.show_sql">true</prop>
    <!-- 自动更新数据库
     <prop key="hibernate.hbm2ddl.auto">update</prop>
    -->
   </props>
  </property>
  <property name="mappingResources">
   <list>
    <value>config/hibernate/Demo-hibernate.hbm.xml</value>
   </list>
  </property>
 </bean>

 <import resource="config/spring/Demo-spring.xml" />
 </beans>

-----------------------------------------------------------------------------------------------------Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <!-- 创建对象的工作交给spring去做 -->
 <constant name="struts.objectFactory" value="spring"></constant>
 <include file="config/struts/Demo-struts.xml" />
</struts>
----------------------------------------------------------------------------------------------Demo-hibernate.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.longtop.demo.Demo" table="DEMO" schema="SCOTT">
        <id name="id" type="java.lang.String">
            <column name="ID" length="32" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="32" />
        </property>
        <property name="age" type="java.lang.String">
            <column name="AGE" length="32" />
        </property>
        <property name="memo" type="java.lang.String">
            <column name="MEMO" length="32" />
        </property>
    </class>
</hibernate-mapping>
------------------------------------------------------------------------------------------------Demo-struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

 <!-- 以下是关于stockauditing的配置 -->
 <!-- 数据访问层 -->
 <!-- dao -->
 <bean id="DemoDAO" class="com.longtop.demo.DemoDAO">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
 </bean>
 <!-- Action配置 -->
 <bean id="DemoAction" class="com.longtop.demo.DemoAction">
  <property name="demodao">
   <ref bean="DemoDAO" />
  </property>
 </bean>
</beans>

-----------------------------------------------------------------------------------------------Demo-struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
     "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <package name="demoaction" extends="struts-default" namespace="/test">
  <action name="demoaction"
   class="DemoAction">
   <result name="success">
           /DemoList.jsp 
   </result>
  </action>
 </package>
</struts>

-------------------------------------------------------------------------------------------------------DemoList.js

Ext.onReady(function() {
 var myStore = new Ext.data.Store({
    reader : new Ext.data.JsonReader({
       totalProperty : 'results',
       root : "items",
       id : "id"
      }, Ext.data.Record.create([{
         name : "id"
        }, {
         name : "name"
        }, {
         name : "age"
        }, {
         name : "memo"
        }
        ])),
    proxy : new Ext.data.HttpProxy({
       url : "test/demoaction!listDemo.action"
      })
   });
 // 创建工具栏组件
 var toolbar = new Ext.Toolbar([{
    text : '新增个人资料信息',
    iconCls : 'add',
    handler : ChannelGroup
   }, {
    text : '修改个人资料信息',
    iconCls : 'option',
    handler : showModifyBookType
   }, {
    text : '删除个人资料信息',
    iconCls : 'remove',
    handler : showDeleteBookType
   },{
    text : '倒出Excel',
    iconCls : 'showDemo',
    handler : showDemoExcel
   },{
    text : '倒入Excel',
    iconCls : 'InDemo',
    handler : InDemoExcel
   }]);

 store : myStore.load({
    params : {
     // 分页从第0条开始
     start : 0,
     // 到第10条结束
     limit : 5
    }
   });
 var cb = new Ext.grid.CheckboxSelectionModel({});
 var myGrid = new Ext.grid.GridPanel({
    applyTo : "DemoList",
    title : "个人资料阅读",
    frame : true,
    width:1200,
                height:400,
    tbar : toolbar,
    store : myStore,
    viewConfig : {
     autoFill : true
    },
    sm : cb,
    columns : [
    new Ext.grid.RowNumberer({
         header : '行号',
         width : 10
        }),// 表格行号组件
      cb, {
       header : "个人资料Id",
       width : 1,
       sortable : true,
       dataIndex : "id"
      }, {
       header : "个人资料姓名",
       width : 1,
       sortable : true,
       dataIndex : "name"
      }, {
       header : "年龄",
       width : 1,
       sortable : true,
       dataIndex : "age",
       renderer : toHref
      }, {
       header : "描述",
       width : 1,
       sortable : true,
       dataIndex : "memo"

      }],
    bbar : new Ext.PagingToolbar({
       // 限制每页显示数量
       pageSize : 5,
       // 引存储器位置
       store : myStore,
       // 是否显示分页条的Msg信息
       displayInfo : true,
       // 提示总记录数
       displayMsg : '显示第 {0} 条到 {1} 条记录,一共 {2} 条',
       // 空记录提示
       emptyMsg : "没有记录"
      })
   });
 function toHref(s, m, rec) {
  return '<a href=' + rec.data.age + ' target=_blank>' + s + '</a>'
 }

 // 创建新增或修改个人资料的form表单
 Ext.QuickTips.init();
 Ext.form.Field.prototype.msgTarget = 'side';// 统一指定错误信息提示方式
 var bookTypeForm = new Ext.FormPanel({
    labelSeparator : ":",
    frame : true,
    border : false,
    items : [ {
       xtype : 'hidden',
       width : 200,
       allowBlank : false,
       blankText : '个人资料ID不能为空',
       name : 'id',
       fieldLabel : 'ID'
      },{
       xtype : 'textfield',
       width : 200,
       allowBlank : false,
       blankText : '个人资料姓名不能为空',
       name : 'name',
       fieldLabel : '姓名'
      }, {
       xtype : 'textfield',
       width : 200,
       allowBlank : false,
       blankText : '年龄不能为空',
       name : 'age',
       fieldLabel : '年龄'
      }, {
       xtype : 'textfield',
       width : 200,
       allowBlank : false,
       blankText : '描述不能为空',
       name : 'memo',
       fieldLabel : '描述'
      }],
    buttons : [{
       text : '关闭',
       handler : function() {
        win.hide();
       }
      }, {
       text : '提交',
       handler : submitForm
      }]
   });
 // 创建弹出窗口
 var win = new Ext.Window({
    layout : 'fit',
    width : 380,
    height : 200,
    modal : true,
    bodyStyle : 'padding:5 5 5 5',
    items : [bookTypeForm]
   });
 // 显示新建书籍类型窗口
 function ChannelGroup() {
  bookTypeForm.form.reset();
  bookTypeForm.isAdd = true;
  win.setTitle("新增个人资料信息");
  win.show();
 }
 
 
 // 显示修改书籍类型窗口
 function showModifyBookType() {
  var bookTypeList = getdemoIdList();
  var num = bookTypeList.length;
  if (num > 1) {
   Ext.MessageBox.alert("提示", "每次只能修改一条信息。")
  } else if (num == 1) {
   bookTypeForm.isAdd = false;
   win.setTitle("修改个人资料信息");
   win.show();
   var demoId = bookTypeList[0];
   loadForm(demoId);
  }
 }
 // 显示删除个人资料对话框
     function showDeleteBookType() {
  var bookTypeList = getdemoIdList();
  var num = bookTypeList.length;
  if (num > 1) {
   Ext.MessageBox.confirm("提示", "您确定要删除"+num+"条个人资料吗?", function(btnId) {
      if (btnId == 'yes') {
       deleteBookType(bookTypeList,num);
      }
     })
  } else if (num == 1) {
   Ext.MessageBox.confirm("提示", "您确定要删除所选个人资料吗?", function(btnId) {
      if (btnId == 'yes') {
       var demoId = bookTypeList[0];
       deleteBookType(demoId,num);
      }
     })
  }
 }
 
 
 // 删除个人资料
 function deleteBookType(bookTypeList,num) {
  var demoId;
  if(num>1){
   for (var i = 0; i < bookTypeList.length; i++) {
    demoId += "@"+bookTypeList[i];
   } 
  }
  else{
    demoId = bookTypeList;
  }
  var msgTip = Ext.MessageBox.show({
     title : '提示',
     width : 250,
     msg : '正在删除个人资料请稍后......'
    });
  Ext.Ajax.request({
   url : "test/demoaction!deleteDemo.action",
   params : {
    demoId : demoId
   },
   method : 'POST',
   success : function(response, options) {
    msgTip.hide();
    var result = Ext.util.JSON.decode(response.responseText);
    if (result.success) {
     // 服务器端数据成功删除后,同步删除客户端列表中的数据
     Ext.Msg.alert('提示', '删除'+ result.num +'条个人资料成功。');
     if(num>1){
           for (var i = 0; i < num; i++) {
           var index = myStore.find('id',bookTypeList[i]);
           if (index != -1) {
         var rec = myStore.getAt(index)
         myStore.remove(rec);
        }
        }
     }
     else{
      var index = myStore.find('id', demoId);
      if (index != -1) {
       var rec = myStore.getAt(index)
       myStore.remove(rec);
      }
     }
    } else {
     Ext.Msg.alert('提示', '该个人资料类型已包含' + result.num + '本个人资料信息不能删除!');
    }
   },
   faelure : function(response, options) {
    msgTip.hide();
    Ext.Msg.alert('提示', '删除个人资料请求失败!');
   }
  });
 }
 
 
 // 加载表单数据
 function loadForm(demoId) {
  bookTypeForm.form.load({
     waitMsg : '正在加载数据请稍后',// 提示信息
     waitTitle : '提示',// 姓名
     url : "test/demoaction!selectDemo.action",// 请求的url地址
     params : {
      demoId : demoId
     },
     method : 'GET',// 请求方式
     success : function(form, action) {// 加载成功的处理函数
      Ext.Msg.alert('提示', '数据加载成功');
     },
     failure : function(form, action) {// 加载失败的处理函数
      Ext.Msg.alert('提示', '数据加载失败');
     }
    });
 }
 // 提交表单数据
 function submitForm() {
  // 判断当前执行的提交操作,isAdd为true表示执行个人资料类型新增操作,false表示执行个人资料类型修改操作
  if (bookTypeForm.isAdd) {
   // 新增个人资料信息
   bookTypeForm.form.submit({
      clientValidation : true,// 进行客户端验证
      waitMsg : '正在提交数据请稍后',// 提示信息
      waitTitle : '提示',// 姓名

      url : "test/demoaction!insertDemo.action",
      // 请求的url地址

      method : 'POST',// 请求方式
      success : function(form, action) {// 加载成功的处理函数
       win.hide();
       updateBookList(action.result.demoId);
       Ext.Msg.alert('提示', '新增个人资料组频道成功');
      },
      failure : function(form, action) {// 加载失败的处理函数
       Ext.Msg.alert('提示', '新增个人资料组频道失败');
      }
     });
  } else {
   // 修改个人资料信息
   bookTypeForm.form.submit({
      clientValidation : true,// 进行客户端验证
      waitMsg : '正在提交数据请稍后',// 提示信息
      waitTitle : '提示',// 姓名
      url : 'test/demoaction!updateDemo.action',// 请求的url地址
      method : 'POST',// 请求方式
      success : function(form, action) {// 加载成功的处理函数
       var index = myStore.find('id', action.result.demoId);
       if (index != -1) {
        var rec = myStore.getAt(index)
        myStore.remove(rec);
       }
       win.hide();
       updateBookList(action.result.demoId);
       Ext.Msg.alert('提示', '修改个人资料类型成功');
      },
      failure : function(form, action) {// 加载失败的处理函数
       Ext.Msg.alert('提示', '修改个人资料类型失败');
      }
     });
  }
 }
 // 明细数据修改后,同步更新个人资料列表信息
 function updateBookList(demoId) {
  var fields = getFormFieldsObj(demoId);
  var index = myStore.find('id', fields.id);
  if (index != -1) {
   var item = myStore.getAt(index);
   for (var fieldName in fields) {
    item.set(fieldName, fields[fieldName]);
   }
   myStore.commitChanges();
  } else {
   var rec = new Ext.data.Record(fields);
   myStore.add(rec);
  }
 }
 // 取得表单数据
 function getFormFieldsObj(demoId) {
  var fields = bookTypeForm.items;
  var obj = {};
  for (var i = 0; i < fields.length; i++) {
   var item = fields.itemAt(i);
   var value = item.getValue();
   obj[item.name] = value;
  }
  if (Ext.isEmpty(obj['id'])) {
   obj['id'] = demoId;
  }
  return obj;
 }
 // 取得所选个人资料
 function getdemoIdList() {
  var recs = myGrid.getSelectionModel().getSelections();
  var list = [];
  if (recs.length == 0) {
   Ext.MessageBox.alert('提示', '请选择要进行操作的个人资料!');
  } else {
   for (var i = 0; i < recs.length; i++) {
    var rec = recs[i];
    list.push(rec.get('id'))
   }
  }
  return list;
 }
 
 
 //导出Excel
 function showDemoExcel(){
  Ext.Ajax.request({
   url : "test/demoaction!showExcelDemo.action",
   method : 'POST',
   success : function(response, options) {
    var result = Ext.util.JSON.decode(response.responseText);
    if (result.success) {
     Ext.Msg.alert('提示', '导出个人资料成功。导出路径D盘根目录!');
    }
   },
   failure : function(response, options) {
    Ext.Msg.alert('提示', '导出个人资料请求失败!');
   }
  });
 }
 
 //导入Excel
 function InDemoExcel(){
  Ext.Ajax.request({
   url : "test/demoaction!InExcelDemo.action",
   method : 'POST',
   success : function(response, options) {
    var result = Ext.util.JSON.decode(response.responseText);
    if (result.success) {
     Ext.Msg.alert('提示', '导入个人资料成功。');
    }else{
      Ext.Msg.alert('提示', '没有要导入的数据.');
    }
   },
   failure : function(response, options) {
    Ext.Msg.alert('提示', '导入个人资料请求失败!');
   }
  });
 };
});
---------------------------------------------------------------------------------------------DemoList.jsp

<%@ page language="java" pageEncoding="gbk"%>
<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://"
   + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>">

  <title>My JSP 'PageNewsControl.jsp' starting page</title>

  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  <link rel="stylesheet" type="text/css"
   href="<%=basePath%>pagesExt/extjs3.2/resources/css/ext-all.css" />
  <script type="text/javascript"
   src="<%=basePath%>pagesExt/extjs3.2/adapter/ext/ext-base.js"></script>
  <script type="text/javascript"
   src="<%=basePath%>pagesExt/extjs3.2/ext-all.js"></script>
  <script type="text/javascript"
   src="<%=basePath%>pagesExt/extjs3.2/source/locale/ext-lang-zh_CN.js"></script>
  <script type="text/javascript"
   src="<%=basePath%>pagesExt/extjs3.2/ext/themeChange.js"></script>
  <script type="text/javascript" src="<%=basePath%>DemoList.js"></script>
 </head>

 <body>
  <center>
   <div id="DemoList"></div>
  </center>
 </body>
</html>

你可能感兴趣的:(spring,Hibernate,struts,ext,Excel)