java poi 导出多Sheet

  @GetMapping("/exportExcelQuestion")
   @Log("导出问卷Excel")
public void exportExcelQuestion(Integer questionId, HttpServletResponse response, org.apache.catalina.servlet4preview.http.HttpServletRequest request){

    Map<String,List<Map<String,Object>>> reMap=new HashMap<>();
    List<Map<String,Object>> reList=null;
       try {
      List<Map<String,Object>> questionList=questionService.questionByExport(questionId);

      //按用户名称把数据分类   Map的key是用户名称  value 是该用户的数据
       for(Map<String,Object> m:questionList){
           for(Map.Entry<String,Object> k:m.entrySet()){
               if("feedbackNum".equals(k.getKey())){  //按这个字段标识为一个sheet  组装成 Map<String,List<Map<String,Object>>>  一个List<Map<String,Object>为一个sheet 数据
                   if(!reMap.containsKey(k.getValue().toString())){   //如果这条用户信息不存在map
                       reList=new ArrayList<>();          //创建一个新的list
                       reList.add(m);                     //把这一条用户调查问卷存到新的list
                       reMap.put(k.getValue().toString(),reList);   //新的用户名称和数据
                   }else{                               //如果存在  ,则把用户信息存到该用户的map的list里去
                     //取出这条用户信息的list   在add进去
                     List<Map<String,Object>> existsList=reMap.get(k.getValue().toString());
                     existsList.add(m);
                   }
               }
           }
       }
          String[] titles = {"用户名称","问卷名称","问题名称","选项名称","文本域回复","答卷时间"};
          String[] elements = {"nickName","questName","subjectName","optionName","optionText","createTime"};

          //导出  多个sheet
           ExportExcel.exportExcelByMoreSheet(titles,elements, reMap,"问卷调查表",response);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

 

//导出工具类

public class ExportExcel{
   public static void exportExcelByMoreSheet(String[] headers,String[] elements,Map<String,List<Map<String,Object>>> reMap,String fileName,
                                          HttpServletResponse response){
    XSSFWorkbook workbook = new XSSFWorkbook();
    int index=0;
    BufferedOutputStream bufferedOutPut =null;
    try {
    for(String i:reMap.keySet()){
         exportExcelBySheet(workbook, index, i,headers,elements, reMap.get(i),fileName,response);
        index++;
    }
    //写入到流里
    OutputStream output = response.getOutputStream();
      bufferedOutPut = new BufferedOutputStream(output);
        workbook.write(bufferedOutPut);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bufferedOutPut!=null){
                bufferedOutPut.flush();
                bufferedOutPut.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void exportExcelBySheet(XSSFWorkbook workbook, int sheetNum, String sheetTitle, String[] headers,String[] elements, List<Map<String,Object>> result,
                       String fileName,HttpServletResponse response) throws Exception {

    // 第一步,创建一个webbook,对应一个Excel以xsl为扩展名文件
    XSSFSheet sheet = workbook.createSheet();
    workbook.setSheetName(sheetNum, sheetTitle);
     //设置列宽度大小
    sheet.setDefaultColumnWidth((short) 25);
     //第二步, 生成表格第一行的样式和字体
    XSSFCellStyle style = workbook.createCellStyle();
    try {
        fileName = URLEncoder.encode(fileName, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    response.setHeader("Content-Disposition", "attachment; filename=" +fileName+".xls");
    response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    XSSFFont font = workbook.createFont();

   //设置字体所在的行高度
    font.setFontHeightInPoints((short) 12);
      // 把字体应用到当前的样式
    style.setFont(font);
     // 指定当单元格内容显示不下时自动换行
    style.setWrapText(true);
      // 产生表格标题行
    XSSFRow row = sheet.createRow(0);
    for (int i = 0; i < headers.length; i++) {
        XSSFCell cell = row.createCell((short) i);
        cell.setCellStyle(style);
        XSSFRichTextString text = new XSSFRichTextString(headers[i]);
        cell.setCellValue(text.toString());
    }
   // 第三步:遍历集合数据,产生数据行,开始插入数据
    if (result != null) {
        int index = 1;
            for(Map<String,Object> map:result){
                row = sheet.createRow(index);
                int cellIndex = 0;
                for(int k = 0; k < elements.length; k++) {
                    //取特定的字段  和表头对应上
                    if(map.containsKey(elements[k])){
                        XSSFCell cell = row.createCell((int) cellIndex);   //创建列
                        System.out.println("map.get(i)==="+map.get(elements[k]).toString());
                        String value=map.get(elements[k]).toString();
                        cell.setCellValue(value+"");
                        cellIndex++;  //行加1
                    }
                }
                index++;   //行加1
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_43075758/article/details/115374589