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

Posted AnswerTheQuestion

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
}

 

以上是关于JAVA操作Excle之Poi批量导出Excle数据的主要内容,如果未能解决你的问题,请参考以下文章

JAVA操作Excle之Poi

如何用JAVA导出Excel?(使用POI)

Excle导出优化

使用Poi对EXCLE的导入导出

POI实现大数据EXCLE导入导出,解决内存溢出问题

Javaweb使用Excle导出数据并下载