欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java导出excel

程序员文章站 2022-06-25 12:08:51
...

很多项目都有导出excel的需求,我稍微整理了一下,使之用起来更方便,希望对大家有帮助。

代码我都整理在了下面这个ExcelUtil里面:

/**
 * Created by solitaryWalker on 2017/12/24.
 */
public class ExcelUtil {

    /**
     * @param headerNameList: excel表头
     * @param mapList:excel内容
     * @param excelName:excel文件名
     */
    public static void writeExcel(HttpServletResponse response,List<String> headerNameList,List<Map<String,Object>> mapList,String excelName){
        // 第一步,创建一个webbook,对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("sheet1");
        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步,创建单元格,并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        for(int i=0;i<headerNameList.size();i++){              //设置表头
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue(headerNameList.get(i));
            cell.setCellStyle(style);
        }
        for(int i=0;i<mapList.size();i++){
            row = sheet.createRow((int) i + 1);
            for(int j=0;j<headerNameList.size();j++){
                row.createCell((short) j).setCellValue(mapList.get(i).get(headerNameList.get(j)).toString());
            }
        }
        try{
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            String fileName =(excelName+sdf.format(new Date())); //此处在excel文件名后面加了一个日期 也可以不加
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            // 设置response参数,可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String((fileName+".xls").getBytes("UTF-8"), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;

            try{
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(out);
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (bis != null)
                    bis.close();
                if (bos != null)
                    bos.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

   public static List<String> getStringList(){
       List<String> stringList=new ArrayList<String>();  //作为表头
       stringList.add("编号");
       stringList.add("姓名");
       stringList.add("身份证");
       stringList.add("性别");
       stringList.add("年龄");
       return stringList;
   }

    public static List<Map<String,Object>> getMapList(){
        List<Map<String,Object>> mapList=new ArrayList<Map<String, Object>>();
        Map<String,Object> map01=new HashMap<String,Object>();
        map01.put("编号","1");
        map01.put("姓名","张三");
        map01.put("身份证","310102195103171000");
        map01.put("性别","男");
        map01.put("年龄","23");
        Map<String,Object> map02=new HashMap<String,Object>();
        map02.put("编号","2");
        map02.put("姓名","李四");
        map02.put("身份证","310102195103171000");
        map02.put("性别","女");
        map02.put("年龄","36");
        mapList.add(map01);
        mapList.add(map02);
        return mapList;
    }

}

使用的时候只需要:

    @RequestMapping(value = "/writeExcel", method = RequestMethod.GET)
    public void writeExcel(HttpServletResponse response) {
        List<String> excelHeaderList = ExcelUtil.getStringList();
        List<Map<String,Object>> excelMapList = ExcelUtil.getMapList();
        String excelName = "导出excel";
        ExcelUtil.writeExcel(response,excelHeaderList,excelMapList,excelName);
    }

效果如下:
java导出excel