码迷,mamicode.com
首页 > 其他好文 > 详细

XSSFWorkbook表格创建工具使用

时间:2020-05-09 16:53:01      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:list   script   实现   center   Servle   tom   格式   asc   新华书店   

1、Api
1、Api
/**
 * 班级签收单Hm导出
 * @param res
 * @param exportClassRecReqDtos
 * @throws IOException
 */
@ApiOperation(value = "班级签收单Hm导出,(qp-参数支持的操作符号有: eq(=),ne(!=),gt(>),lt(<),ge(>=),le(<=),in,like,notLike,likeleft(左边LIKE ‘%xxx‘),likeright(右边LIKE ‘xx%‘)", tags = {
        "classReceiptHm",}, nickname = "exportClassReceiptHmByParams")
@ApiResponses(value = {@ApiResponse(code = 200, message = "操作是否成功,000000:成功,否则失败")})
void exportClassReceiptHmByParams(HttpServletResponse res, List<ExportClassRecReqDto> exportClassRecReqDtos) throws IOException;

2、Controller(实现api)
@Override
@PostMapping(value = "/receiptHm/exportClassReceiptHm",produces = MediaType.APPLICATION_JSON_VALUE)
public void exportClassReceiptHmByParams(HttpServletResponse res,  @RequestBody List<ExportClassRecReqDto> exportClassRecReqDtos) throws IOException {
    XSSFWorkbook wb = classReceiptHmService.exportClassReceiptHmByParams(exportClassRecReqDtos);
    res.setHeader("Content-type","application/vnd.ms-excel");
    res.setCharacterEncoding("UTF-8");
    res.setHeader("Content-Disposition","attachment;filename="+new String("班级签收单Hm".getBytes("UTF-8"),"ISO-8859-1")+".xls");
    wb.write(res.getOutputStream());
}

3、service
/**
 * 班级签收单Hm导出
 * @param exportClassRecReqDtos
 * @return
 */
XSSFWorkbook exportClassReceiptHmByParams(List<ExportClassRecReqDto> exportClassRecReqDtos);

4、serviceImpl
@Override
public XSSFWorkbook exportClassReceiptHmByParams(List<ExportClassRecReqDto> exportClassRecReqDtos) {
    System.out.println(exportClassRecReqDtos);

    Map<String, String> headerNames = new LinkedHashMap<>();

    headerNames.put("serialNum", "序号");
    headerNames.put("studentName", "姓名");
    headerNames.put("studentPhone", "手机号");
    headerNames.put("classNO", "班级");
    headerNames.put("orderNo","订单号");
    headerNames.put("orderStatus","发货状态");
    headerNames.put("unitPrice","定价");
    headerNames.put("sumQty","套数");
    headerNames.put("sumPrice","金额");
    headerNames.put("","签名");

    Map<String,String> otherTableField = new HashMap<>();
    otherTableField.put("gradeId","b.");
    otherTableField.put("classNo","b.");

    Map<String,Class> entities = new HashMap<>();
    entities.put("a.",OrderLinePo.class);
    entities.put("b.", StudentPo.class);
    //创建工作簿
    XSSFWorkbook wb = new XSSFWorkbook();
    //创建一个sheet
    XSSFSheet sheet = wb.createSheet();
    // 创建单元格样式
    XSSFCellStyle style =  wb.createCellStyle();
    //solid 填充
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    //边框加黑
    style.setBorderBottom(BorderStyle.THIN);
    style.setBorderLeft(BorderStyle.THIN);
    style.setBorderRight(BorderStyle.THIN);
    style.setBorderTop(BorderStyle.THIN);
    //定义初始行数
    Integer jsonIndex=0;
    //获取第一行,添加表头
    sheet.addMergedRegion(new CellRangeAddress(0,0,0,headerNames.size()-1));
    XSSFRow startRow = sheet.createRow(jsonIndex++);
    startRow.createCell(0).setCellValue("新华书店网上购书签收表");
    //设置行高
    startRow.setHeight((short)500);
    //设置表头字体居中
    XSSFCellStyle startCellStyle = wb.createCellStyle();
    startCellStyle.setAlignment(HorizontalAlignment.CENTER);
    startRow.getCell(0).setCellStyle(startCellStyle);
    //获取第二行,为每一列添加字段
    XSSFRow row1 = sheet.createRow(jsonIndex++);
    Integer index = 0;
    for(Map.Entry<String,String> headerName : headerNames.entrySet()){
        row1.createCell(index).setCellValue(headerName.getValue());
        index ++;
    }

    Map<String,Object> params = new HashMap<>();
    //用于接收购买的套数
    Integer qty = new Integer(0);
    //用于接收总金额
    BigDecimal totalPrice = new BigDecimal(0);
    //生成格式化时间
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String nowTime = sdf.format(new Date());
    //遍历传来的班级信息集合
    for (ExportClassRecReqDto exportClassRecReqDto : exportClassRecReqDtos){
        String classNOs = exportClassRecReqDto.getClassNos();
        //将班级id字符串拆分成单个班级进行处理
        List<String> classNoList = Arrays.asList(classNOs.split(","));
        params.put("qp-schoolId-eq",exportClassRecReqDto.getSchoolId());
        params.put("qp-gradeId-eq",exportClassRecReqDto.getGradeId());
        for (String classNO : classNoList){
            params.put("qp-classNo-eq",classNO);
            QueryWrapper wrapper = QueryParamUtils.getMultiEntityWrapper(params, otherTableField, entities, "a.");
            List<ExportClassRecResHmDto> exportClassRecResHmDtos = classReceiptHmMapper.exportClassReceiptHmByParams( wrapper);
            //统计总金额
            BigDecimal sumMoney = new BigDecimal(0);
            for (ExportClassRecResHmDto exportClassRecResHmDto : exportClassRecResHmDtos) {
                qty = exportClassRecResHmDto.getQty();
                if (exportClassRecResHmDto.getRefundQty() == null) exportClassRecResHmDto.setRefundQty(0);
                exportClassRecResHmDto.setSumQty(qty - exportClassRecResHmDto.getRefundQty());
                totalPrice = exportClassRecResHmDto.getTotalPrice();
                if (exportClassRecResHmDto.getRefundApplyTotal() == null)
                    exportClassRecResHmDto.setRefundApplyTotal(NumberUtils.toScaledBigDecimal(0.00));
                exportClassRecResHmDto.setSumPrice(totalPrice.subtract(exportClassRecResHmDto.getRefundApplyTotal()));
                sumMoney = sumMoney.add(exportClassRecResHmDto.getSumPrice());
            }
            JSONArray data = JSONArray.parseArray(JSON.toJSONString(exportClassRecResHmDtos));

            //添加每个班的头部信息
            String cellInfo = "学校:"+exportClassRecResHmDtos.get(0).getSchoolName()+" "+
                    "年级:"+exportClassRecReqDto.getGradeId()+" "+
                    "班级:"+exportClassRecResHmDtos.get(0).getClassNO()+" "+
                    "订单数:"+exportClassRecResHmDtos.size()+" "+
                    "统计时间:"+nowTime;
            sheet.addMergedRegion(new CellRangeAddress(jsonIndex,jsonIndex,0,headerNames.size()-5));
            sheet.createRow(jsonIndex++).createCell(0).setCellValue(cellInfo);
            //将数据写入表
            for(Integer thisIndex = 0 ; thisIndex < data.size(); ++thisIndex ){
                JSONObject jsonObject = data.getJSONObject(thisIndex);
                XSSFRow row = sheet.createRow(jsonIndex);
                Integer cellIndex = 0;
                for(Map.Entry<String,String> stringStringEntry : headerNames.entrySet()){
                    Object str = jsonObject.get(stringStringEntry.getKey());
                    String cellValue = "-";
                    if(str != null){
                        cellValue = str.toString();
                    }
                    row.createCell(cellIndex ++).setCellValue(cellValue);

                }
                jsonIndex++;
            }
            //添加每个班的尾部
            sheet.addMergedRegion(new CellRangeAddress(jsonIndex,jsonIndex,0,headerNames.size()-4));
            XSSFRow endRow = sheet.createRow(jsonIndex++);
            endRow.createCell(0).setCellValue("合计:");
            endRow.createCell(headerNames.size()-3).setCellValue(exportClassRecResHmDtos.size());
            endRow.createCell(headerNames.size()-2).setCellValue(sumMoney.floatValue());

            sheet.addMergedRegion(new CellRangeAddress(jsonIndex,jsonIndex,0,headerNames.size()-1));
            sheet.createRow(jsonIndex++).createCell(0)
                    .setCellValue(cellInfo);
            sheet.createRow(jsonIndex++);
        }

    }
    return wb;
}

 

2、Controller(实现api)
@Override
@PostMapping(value = "/receiptHm/exportClassReceiptHm",produces = MediaType.APPLICATION_JSON_VALUE)
public void exportClassReceiptHmByParams(HttpServletResponse res,  @RequestBody List<ExportClassRecReqDto> exportClassRecReqDtos) throws IOException {
    XSSFWorkbook wb = classReceiptHmService.exportClassReceiptHmByParams(exportClassRecReqDtos);
    res.setHeader("Content-type","application/vnd.ms-excel");
    res.setCharacterEncoding("UTF-8");
    res.setHeader("Content-Disposition","attachment;filename="+new String("班级签收单Hm".getBytes("UTF-8"),"ISO-8859-1")+".xls");
    wb.write(res.getOutputStream());
}

 

3、service
/**
 * 班级签收单Hm导出
 * @param exportClassRecReqDtos
 * @return
 */
XSSFWorkbook exportClassReceiptHmByParams(List<ExportClassRecReqDto> exportClassRecReqDtos);

 

4、serviceImpl
@Override
public XSSFWorkbook exportClassReceiptHmByParams(List<ExportClassRecReqDto> exportClassRecReqDtos) {
    System.out.println(exportClassRecReqDtos);

    Map<String, String> headerNames = new LinkedHashMap<>();

    headerNames.put("serialNum", "序号");
    headerNames.put("studentName", "姓名");
    headerNames.put("studentPhone", "手机号");
    headerNames.put("classNO", "班级");
    headerNames.put("orderNo","订单号");
    headerNames.put("orderStatus","发货状态");
    headerNames.put("unitPrice","定价");
    headerNames.put("sumQty","套数");
    headerNames.put("sumPrice","金额");
    headerNames.put("","签名");

    Map<String,String> otherTableField = new HashMap<>();
    otherTableField.put("gradeId","b.");
    otherTableField.put("classNo","b.");

    Map<String,Class> entities = new HashMap<>();
    entities.put("a.",OrderLinePo.class);
    entities.put("b.", StudentPo.class);
    //创建工作簿
    XSSFWorkbook wb = new XSSFWorkbook();
    //创建一个sheet
    XSSFSheet sheet = wb.createSheet();
    // 创建单元格样式
    XSSFCellStyle style =  wb.createCellStyle();
    //solid 填充
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    //边框加黑
    style.setBorderBottom(BorderStyle.THIN);
    style.setBorderLeft(BorderStyle.THIN);
    style.setBorderRight(BorderStyle.THIN);
    style.setBorderTop(BorderStyle.THIN);
    //定义初始行数
    Integer jsonIndex=0;
    //获取第一行,添加表头
    sheet.addMergedRegion(new CellRangeAddress(0,0,0,headerNames.size()-1));
    XSSFRow startRow = sheet.createRow(jsonIndex++);
    startRow.createCell(0).setCellValue("新华书店网上购书签收表");
    //设置行高
    startRow.setHeight((short)500);
    //设置表头字体居中
    XSSFCellStyle startCellStyle = wb.createCellStyle();
    startCellStyle.setAlignment(HorizontalAlignment.CENTER);
    startRow.getCell(0).setCellStyle(startCellStyle);
    //获取第二行,为每一列添加字段
    XSSFRow row1 = sheet.createRow(jsonIndex++);
    Integer index = 0;
    for(Map.Entry<String,String> headerName : headerNames.entrySet()){
        row1.createCell(index).setCellValue(headerName.getValue());
        index ++;
    }

    Map<String,Object> params = new HashMap<>();
    //用于接收购买的套数
    Integer qty = new Integer(0);
    //用于接收总金额
    BigDecimal totalPrice = new BigDecimal(0);
    //生成格式化时间
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String nowTime = sdf.format(new Date());
    //遍历传来的班级信息集合
    for (ExportClassRecReqDto exportClassRecReqDto : exportClassRecReqDtos){
        String classNOs = exportClassRecReqDto.getClassNos();
        //将班级id字符串拆分成单个班级进行处理
        List<String> classNoList = Arrays.asList(classNOs.split(","));
        params.put("qp-schoolId-eq",exportClassRecReqDto.getSchoolId());
        params.put("qp-gradeId-eq",exportClassRecReqDto.getGradeId());
        for (String classNO : classNoList){
            params.put("qp-classNo-eq",classNO);
            QueryWrapper wrapper = QueryParamUtils.getMultiEntityWrapper(params, otherTableField, entities, "a.");
            List<ExportClassRecResHmDto> exportClassRecResHmDtos = classReceiptHmMapper.exportClassReceiptHmByParams( wrapper);
            //统计总金额
            BigDecimal sumMoney = new BigDecimal(0);
            for (ExportClassRecResHmDto exportClassRecResHmDto : exportClassRecResHmDtos) {
                qty = exportClassRecResHmDto.getQty();
                if (exportClassRecResHmDto.getRefundQty() == null) exportClassRecResHmDto.setRefundQty(0);
                exportClassRecResHmDto.setSumQty(qty - exportClassRecResHmDto.getRefundQty());
                totalPrice = exportClassRecResHmDto.getTotalPrice();
                if (exportClassRecResHmDto.getRefundApplyTotal() == null)
                    exportClassRecResHmDto.setRefundApplyTotal(NumberUtils.toScaledBigDecimal(0.00));
                exportClassRecResHmDto.setSumPrice(totalPrice.subtract(exportClassRecResHmDto.getRefundApplyTotal()));
                sumMoney = sumMoney.add(exportClassRecResHmDto.getSumPrice());
            }
            JSONArray data = JSONArray.parseArray(JSON.toJSONString(exportClassRecResHmDtos));

            //添加每个班的头部信息
            String cellInfo = "学校:"+exportClassRecResHmDtos.get(0).getSchoolName()+" "+
                    "年级:"+exportClassRecReqDto.getGradeId()+" "+
                    "班级:"+exportClassRecResHmDtos.get(0).getClassNO()+" "+
                    "订单数:"+exportClassRecResHmDtos.size()+" "+
                    "统计时间:"+nowTime;
            sheet.addMergedRegion(new CellRangeAddress(jsonIndex,jsonIndex,0,headerNames.size()-5));
            sheet.createRow(jsonIndex++).createCell(0).setCellValue(cellInfo);
            //将数据写入表
            for(Integer thisIndex = 0 ; thisIndex < data.size(); ++thisIndex ){
                JSONObject jsonObject = data.getJSONObject(thisIndex);
                XSSFRow row = sheet.createRow(jsonIndex);
                Integer cellIndex = 0;
                for(Map.Entry<String,String> stringStringEntry : headerNames.entrySet()){
                    Object str = jsonObject.get(stringStringEntry.getKey());
                    String cellValue = "-";
                    if(str != null){
                        cellValue = str.toString();
                    }
                    row.createCell(cellIndex ++).setCellValue(cellValue);

                }
                jsonIndex++;
            }
            //添加每个班的尾部
            sheet.addMergedRegion(new CellRangeAddress(jsonIndex,jsonIndex,0,headerNames.size()-4));
            XSSFRow endRow = sheet.createRow(jsonIndex++);
            endRow.createCell(0).setCellValue("合计:");
            endRow.createCell(headerNames.size()-3).setCellValue(exportClassRecResHmDtos.size());
            endRow.createCell(headerNames.size()-2).setCellValue(sumMoney.floatValue());

            sheet.addMergedRegion(new CellRangeAddress(jsonIndex,jsonIndex,0,headerNames.size()-1));
            sheet.createRow(jsonIndex++).createCell(0)
                    .setCellValue(cellInfo);
            sheet.createRow(jsonIndex++);
        }

    }
    return wb;
}

 




XSSFWorkbook表格创建工具使用

标签:list   script   实现   center   Servle   tom   格式   asc   新华书店   

原文地址:https://www.cnblogs.com/KelvinDaniels/p/12858314.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!