JAVA操作Excle之Poi(二)批量导出Excle数据

批量导入:

界面JS:导出当前数据带参数

function exportStudent(){
    $.messager.confirm('确认对话框', '确认要导出当前所有数据吗?', function(r){
        if (r){
            var name=$("#nameLike").val();
            var i=$('#sc').combobox("getValue");
            var sex=$("#sexLike").combobox("getValue");
            var address=$("#AddressLike").val();
            window.open("${pageContext.request.contextPath }/student/exportStudent.do?likeName="+name+"&sclassId="+i+"&sex="+sex+"&addressLike="+address+"");
        }
    });
}

 后台逻辑:

@RequestMapping("/exportStudent")
    public String exportStudent(@RequestParam(value="likeName",required=false) String likeName,@RequestParam(value="sclassId",required=false) Integer sclassId,@RequestParam(value="sex",required=false) String sex,@RequestParam(value="addressLike",required=false) String addressLike,HttpServletResponse response){
        Map<String, Object> param=new HashMap<String, Object>();
        if(StringUtil.getBoolean(likeName)){
            param.put("name", "%"+likeName.trim()+"%");
        }
        if(StringUtil.getBoolean(sex)){
            param.put("sex", sex);
        }
        if(sclassId!=null){
            param.put("sclassId", sclassId);
        }
        if(StringUtil.getBoolean(addressLike)){
            List<Address> AddresLikeList=addressService.findByLikeAddress(addressLike);
            List<Integer> strList=new ArrayList<Integer>();
            for(int i=0;i<AddresLikeList.size();i++){    
                strList.add(AddresLikeList.get(i).getId());
            }
            param.put("addressId", strList);
        }
        List<Student> list=studentService.findAll(param);//查出list集合
        List<Map<String, Object>> map=createExcelRecord(list);//利用自己私有方法获得Map集合
        Workbook wb=new HSSFWorkbook();
        String headers[]={"学号","姓名","性别","年龄","班级","籍贯","生日"};
        try {
            ExcelUtil.fillExcelData(map, wb, headers);//参照下面的工具类
            Date date=DateUtil.getDate();
            String d=DateUtil.formatDate(date, "yyyyMMddHHmmss");//参照下面的工具类
            ResponseUtil.export(response, wb, "学生信息"+d);//参照下面的工具类
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        return null;
    }
    
    //内部方法
     private List<Map<String, Object>> createExcelRecord(List<Student> list) {
            List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
            Student student=null;
            for (int j = 0; j < list.size(); j++) {
                student=list.get(j);
                Map<String, Object> mapValue = new HashMap<String, Object>();
                mapValue.put("学号", student.getId());
                mapValue.put("姓名", student.getName());
                mapValue.put("性别", student.getSex());
                mapValue.put("年龄", student.getAge());
                mapValue.put("班级", student.getSclassId().getName());
                mapValue.put("籍贯", student.getAddressId().getSheng()+"省 "+student.getAddressId().getShi()+"市 "+student.getAddressId().getQu());
                mapValue.put("生日", DateUtil.formatDate(student.getBirthday(), "yyyy-MM-dd HH:mm:ss"));
                listmap.add(mapValue);
            }
            return listmap;
        }

工具类:

ExcleUtil

package com.maya.util;

import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class ExcelUtil {

    public static void fillExcelData(List<Map<String, Object>> list,Workbook wb,String[] headers)throws Exception{
        int rowIndex=0;
        Sheet sheet=wb.createSheet();
        Row row=sheet.createRow(rowIndex++);
        for(int i=0;i<headers.length;i++){
            row.createCell(i).setCellValue(headers[i]);
        }
        for(int i=0;i<list.size();i++){
            row=sheet.createRow(rowIndex++);
            for(int j=0;j<headers.length;j++){
                row.createCell(j).setCellValue(list.get(i).get(headers[j]) == null?" ": list.get(i).get(headers[j]).toString());
            }
        }
    }
}

ResponseUtil

package com.maya.util;

import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;

public class ResponseUtil {
public static void export(HttpServletResponse response,Workbook wb,String fileName)throws Exception{
        response.setHeader("Content-Disposition", "attachment;filename="+new String((fileName + ".xls").getBytes("utf-8"),"iso8859-1"));
        response.setContentType("application/ynd.ms-excel;charset=UTF-8");
        OutputStream out=response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();
    }
}

DateUitil

package com.maya.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.springframework.stereotype.Component;

public class DateUtil {
    
    public static Date getDate(){
        Calendar c=Calendar.getInstance();
        return c.getTime();
    }
    
    public static String formatDate(Date date,String format){
        String result="";
        SimpleDateFormat sdf=new SimpleDateFormat(format);
        if(date!=null){
            result=sdf.format(date);
        }
        return result;
    }
    public static Date formatString(String str,String format) throws Exception{
        SimpleDateFormat sdf=new SimpleDateFormat(format);
        return sdf.parse(str);
    }
}

 

转载于:https://www.cnblogs.com/AnswerTheQuestion/p/6792422.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值