1. 程式人生 > >EasyUi、SpringMVC、jquery的ajax、匯出Excel檔案

EasyUi、SpringMVC、jquery的ajax、匯出Excel檔案

後臺Controller中的方法:

package com.lee.springmvc.controller;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lee.springmvc.entity.Student;
import com.lee.springmvc.service.StudentService;
import com.lee.springmvc.util.ExportUtil;
@Controller
public class StudentController {
    @Autowired
    private StudentService studentService;
    
    @RequestMapping(value="pages/studentInfo")
    public ModelAndView studentInfo(){
        //學生資訊 按鈕對應的是  @RequestMapping("pages/studentInfo")的值
        //此方法:跳轉到studentList.jsp頁面   (easyui框架,先跳轉,然後在取值。是非同步請求)
        ModelAndView mav = new ModelAndView();
//        mav.setViewName("aa");
        mav.setViewName("studentList");
        mav.addObject("type", 0);//剛進來的時候預設是 0 
        return mav;
    }
    
    @RequestMapping(method=RequestMethod.POST, value = "pages/getStudentList", consumes = "application/json;charset=UTF-8")
    @ResponseBody
    public String getStudentList(int page, int rows){
        System.out.println("page = "+page+",   rows = "+rows);
        //page   rows   這兩個引數從前臺傳過來 
        //前臺 easyui執行分頁時向後臺傳去兩個引數,一個就是當前頁數另一個就是每頁顯示行數(封裝好了的)
        List<Student> slist = studentService.list(page, rows);
        int total = studentService.getTotal();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("total", total);
        map.put("rows", slist);
        map.put("type", 0);//剛進來的時候預設是 0 ;
        return JSONObject.fromObject(map).toString();//前臺要的是json物件格式的資料
    }

    /***
     * 新增操作
     * @param stu
     * @return
     * @throws Exception
     */
    @RequestMapping(value="pages/saveStudent")  
    @ResponseBody  
    public String saveStudent(Student stu) throws Exception{  
        System.out.println("儲存的資料是:" + stu);
        String msg = "操作失敗!";
        boolean flag = false;
        try {  
            flag = studentService.addStudent(stu);
            msg = "操作成功!";
        } catch (Exception e) {  
            e.printStackTrace();  
            msg = "操作失敗";  
            throw e;  
        } 
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("flag", flag);
        modelMap.put("msg", msg);
        modelMap.put("type", 1);// 1  代表  顯示新增事件對應的按鈕(新增)
        return JSONObject.fromObject(modelMap).toString();
    }  
    
    /***
     * 修改 -- 根據sid查詢單條資料
     * @param sid
     * @return
     */
    @RequestMapping(value = "pages/editData", method = RequestMethod.POST)
    @ResponseBody
    public String editStudentInfo(String sid) {
        Student result = studentService.getSingle(sid);
        System.out.println("修改的資料是:"+result.toString());
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("result", result);
        modelMap.put("type", 2);// 2  代表  顯示修改事件對應的按鈕(修改)
        return JSONObject.fromObject(modelMap).toString();
    }
    
    /***
     * 修改 -- 根據sid 修改 單條資料
     * @param sid
     * @return
     */
    @RequestMapping(value = "pages/updateStu", method = RequestMethod.POST)
    @ResponseBody
    public String updateStu(Student stu) {
        System.out.println("要修改的資料是:" + stu);
        String msg = "操作失敗!";
        boolean flag = false;
        try {  
            flag = studentService.updateStudent(stu);
            msg = "操作成功!";
        } catch (Exception e) {  
            e.printStackTrace();  
            msg = "操作失敗";  
            throw e;  
        } 
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("flag", flag);
        modelMap.put("msg", msg);
        modelMap.put("type", 2);// 2  代表  顯示修改事件對應的按鈕(修改)
    //    ModelAndView mav = new ModelAndView();
    //    mav.addObject("type", 2);//剛進來的時候預設是 0 
        return JSONObject.fromObject(modelMap).toString();
    }

    /***
     * 讀取資料庫,放到list中 並匯出Excel
     * @param page 當前頁數
     * @param rows  每頁的記錄數(行數)
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "<strong><span style="color:#FF0000;">pages/getStudentExport</span></strong>", method = RequestMethod.POST)
    @ResponseBody
    public String <span style="color:#FF0000;"><strong>getStudentExport</strong></span>(int page, int rows) throws Exception{
        System.out.println("---------page = "+page+",   rows = "+rows);
        
//        String[] strs = {"學生Id","學生編號","學生姓名","性    別","年齡","出生日期","愛好"};
//        HSSFWorkbook workbook = ExportUtil.getHSSFWorkbook(strs, stuName, values);
//        return workbook;
        //第一步建立一個webbook ,對應一個Excel檔案
        HSSFWorkbook webBook = new HSSFWorkbook();
        //第二步,在webbook中添 新增一個sheet 對應的Excel 檔案中的sheet
        HSSFSheet sheet = webBook.createSheet("學生資訊表");
        //第三步,在sheet中新增表頭 第 0 行(從 0 開始的),老版本的poi 對Excel的行數列數有限制 short
        HSSFRow row = sheet.createRow((int)0);
        //第四步,建立單元格,並設定表頭居中
        HSSFCellStyle style = webBook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//建立一個居中格式
        HSSFCell cell = null;
        String[] strs = {"學生Id","學生編號","學生姓名","性    別","年齡","出生日期","愛好"};
        for (int i = 0; i < strs.length; i++) {
//            row.createCell((short)1).setCellValue("工單數");
            cell = row.createCell(i); 
            cell.setCellValue(strs[i]);
            cell.setCellStyle(style);
        }
        //第五步  寫入實體資料 實際應用中這些資料從資料庫得到
        List<Student> list = <strong><span style="color:#FF0000;">studentService.list(page, rows);</span></strong>
//        List<Object> values = new ArrayList<Object>();
        String stuName = "學生資訊";
//        Iterator it = list.iterator();
//        while(it.hasNext()){
//            Student stu = (Student) it.next();
//            /*int sid = stu.getSid();
//            String stunum = stu.getStunum();
//            String name = stu.getStuname();
//            String stuage = stu.getStuage();
//            String stusex = stu.getStusex();
//            String stubirthday = stu.getStubirthday();
//            String stuhobby = stu.getStuhobby();*/
//            values.add(stu);
//        }
        for (int i = 0; i < list.size(); i++) {
//            String name = list.get(i).getStuname();
//            values.add(list.get(i));
            Student stu = new Student();
            stu = list.get(i);
            row = sheet.createRow((int) i + 1 );
            //第四步, 建立單元格,並設定值
            row.createCell(0).setCellValue((int)stu.getSid());
            row.createCell(1).setCellValue((String)stu.getStunum());
            row.createCell(2).setCellValue((String)stu.getStuname());
            row.createCell(3).setCellValue((String)stu.getStusex());
            row.createCell(4).setCellValue((String)stu.getStuage());
            row.createCell(5).setCellValue((String)stu.getStubirthday());
//            row.createCell(6).setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu.getStuhobby()));
            row.createCell(6).setCellValue(stu.getStuhobby());
        }
        String msg = "操作失敗!";
        boolean flag = false;
        //第六步 將檔案存放到指定位置
        try{
            FileOutputStream fout = new FileOutputStream("E:/Students.xls");
            webBook.write(fout);
            fout.close();
            flag = true;
            msg = "操作成功!";
        }catch(Exception e){
            e.printStackTrace();
            msg = "操作失敗";  
            throw e;  
        }
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("flag", flag);
        modelMap.put("msg", msg);
        return JSONObject.fromObject(modelMap).toString();
    }
    
    
    
    

}





對應的DAO實現方法:

<span style="font-size:18px;">package com.lee.springmvc.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.lee.springmvc.dao.StudentDAO;
import com.lee.springmvc.entity.Student;

import java.sql.ResultSet;  
import java.sql.SQLException;
@Repository
public class StudentDAOImpl implements StudentDAO{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public List<Student> listStu(int currentPage, int pageSize) {
//		List<Student> slist = new ArrayList<Student>();
		String sql = "select * from t_student where 1=1" ;
		//判斷某字串是否     不為空   且   長度不為0    且     不由空白符(whitespace) 構成,等於 !isBlank(String str) 
		if(currentPage>0 && pageSize >0){
			sql += " limit " + (currentPage-1)*pageSize +" , "  + pageSize ;
		}
//		List<Student> slist = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Student.class));  
//	    return slist;  
	    return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
	}
}</span>


ajax的定義形式:

<span style="font-size:18px;">//匯出Excel
function exportMd(){
var grid = $('#t_student');
var options = grid.datagrid('getPager').data("pagination").options;
var page = options.pageNumber;
//var total = options.total;
//var max = Math.ceil(total/options.pageSize);
var rows = options.pageSize;
$.ajax( {  
         type : "POST",  //定義方法型別(get,post)
         url : "action.jsp",  //對應後臺的訪問地址:URL
         data : {
               page:page,
               rows:rows
         },  //往後臺傳送的引數
         dataType : "json",//傳引數的型別
         success : function(data) {
                if(data){
                    if(data.flag){
                        $.messager.alert('提示', data.msg, 'info', function(){
                            $('#t_student').datagrid('reload');
                        });
                    }else{
                        $.messager.alert('提示',data.msg, 'error');
                    }
                }
            },
            error : function(data) {
                $.messager.alert('警告',"匯入Excel資料失敗,請檢查網路!", 'error');
            }
        });
} 

對應的jsp頁面程式碼
<div id="lay" class="easyui-layout" style="width: 100%; height: 100%">
    <div region="center">
        <div id="toolbar"></div>
        <table id="t_student"></table>
    </div>
</div>


</span>