Java 页面表单数据导出Excel

Excel导出

1,代码,
Controllerc层

    @GetMapping("/exportExcel")
    @ResponseBody
    public Object bloodKinshipExportExcel(DataBloodQo qo) throws Exception {
//        excelService.bloodKinshipExportExcel(qo);
        String fileName = URLEncoder.encode("血缘关系.xlsx", "UTF-8");
        try {
            byte [] buff = excelService.bloodKinshipExportExcel(qo);
            response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
            response.setContentType("application/ms-excel");
            ResponseUtil.toDownload(buff, fileName);
            return null;
        } catch (Exception e) {
        	e.printStackTrace();
            return ResponseUtil.toWarningMessage("导出失败", e);
        }
    }

Service层

 byte[] bloodKinshipExportExcel(DataBloodQo qo) throws Exception ;

Service实现层

public byte[] bloodKinshipExportExcel(DataBloodQo qo) throws Exception {
        List<DataBloodRelationVo> list = service.list(qo);
//        Map<String,Object> map = new HashMap<String, Object>();
//        map.put("SrcDbName",list.get(0).getSrcDbName());
//        map.put("AccName",list.get(0).getTargetAccName());
//        map.put("TargetDbName",list.get(0).getTargetDbName());
//        map.put("TargetTableName",list.get(0).getTargetTableName());
        String dataSyncType = list.get(0).getDataSyncType();
        Map<String, Object> map1 = null;
        if (StringUtils.isNotEmpty(dataSyncType)){
             map1 = mapper.listETLTreeNanm(dataSyncType);
        }
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("templates/exportxlxs/formwork.xlsx");
        assert resourceAsStream != null;
        XSSFWorkbook book = new XSSFWorkbook(resourceAsStream);
//        System.out.println("xssfWorkbook对象:" + book);
        //读取第一个工作表
        XSSFSheet sheet = book.getSheetAt(0);
//        System.out.println("sheet对象:" + sheet);
        int maxRow = sheet.getLastRowNum();
        int firstRowNum = sheet.getFirstRowNum();
//        System.out.println("s数: "+firstRowNum);
//        System.out.println("总行数为:" + maxRow);
        XSSFRow row1 = sheet.getRow(0);
        XSSFCell cell = row1.getCell(2);
        cell.setCellValue(list.get(0).getTargetDbName());
        XSSFRow row2 = sheet.getRow(0);
        XSSFCell cell1 = row2.getCell(6);
        cell1.setCellValue(list.get(0).getTargetAccName());
        XSSFRow row3 = sheet.getRow(0);
        XSSFCell cell2 = row3.getCell(10);
        cell2.setCellValue(list.get(0).getTargetTableName());
        XSSFRow sheetRow = sheet.getRow(1);
        XSSFCell xssfCell = sheetRow.getCell(3);
        assert map1 != null;
        xssfCell.setCellValue(ObjectUtils.toString(map1.get("SORT_NM")));
        Map<String, Object> objectMap = mapper.listMeaningName(ObjectUtils.toString(list.get(0).getImplType()));
        XSSFRow sheetRow1 = sheet.getRow(1);
        XSSFCell xssfCell1 = sheetRow1.getCell(6);
        xssfCell1.setCellValue(ObjectUtils.toString(objectMap.get("CODE_MEANING")));
        XSSFRow row4 = sheet.getRow(2);
        XSSFCell cell4 = row4.getCell(2);
        cell4.setCellValue(list.get(0).getTableDesc());
        List<ColBloodInfoVo> colBloodInfoList = list.get(0).getColBloodInfoList();
       List<SrcColumnVo> srcColumnVoList = colBloodInfoList.get(0).getSrcColumnVoList();
        for (int i = 0 ;i<colBloodInfoList.size();i++){

            XSSFRow xssfRow = sheet.createRow(5+i);
            copyRow(book, sheet.getRow(4+i), xssfRow, false);

                XSSFCell rowCell = xssfRow.getCell(1);
                rowCell.setCellValue(colBloodInfoList.get(i).getTargetColumnName());
                XSSFRow xssfRow1 = sheet.getRow(5+i);
                XSSFCell rowCell1 = xssfRow1.getCell(4);
                rowCell1.setCellValue(colBloodInfoList.get(i).getColumnDesc());
                XSSFRow xssfRow7 = sheet.getRow(5+i);
                XSSFCell row1Cell1 = xssfRow7.getCell(0);
                row1Cell1.setCellValue(i);
                XSSFRow xssfRow2 = sheet.getRow(5+i);
                XSSFCell row1Cell = xssfRow2.getCell(5);
                row1Cell.setCellValue(colBloodInfoList.get(i).getExpression());
                XSSFRow xssfRow3 = sheet.getRow(5+i);
                XSSFCell row2Cell = xssfRow3.getCell(6);
                row2Cell.setCellValue(StringUtils.strip(list.get(0).getSrcDbName(),","));
                XSSFRow xssfRow4 = sheet.getRow(5+i);
                XSSFCell row3Cell = xssfRow4.getCell(7);
                row3Cell.setCellValue(StringUtils.strip(list.get(0).getSrcAccName(),","));
                XSSFRow xssfRow5 = sheet.getRow(5+i);
                XSSFCell row4Cell = xssfRow5.getCell(8);
                row4Cell.setCellValue(StringUtils.strip(list.get(0).getSrcTableName(),","));
                XSSFRow xssfRow6 = sheet.getRow(5+i);
                XSSFCell row5Cell = xssfRow6.getCell(9);

                row5Cell.setCellValue(colBloodInfoList.get(i).getSrcColumnVoList().get(0).getSrcColumnName());
        }
        // 新建一个输出流把填充过的excel输出到d盘下
        ByteArrayOutputStream out = new ByteArrayOutputStream();
            book.write(out);
            out.close();
            book.close();
//        for (int row = 0; row <= maxRow; row++) {
//            //获取最后单元格num,即总单元格数 ***注意:此处从1开始计数***
//            int maxRol = sheet.getRow(row).getLastCellNum();
//
//            System.out.println("--------第" + row + "行的数据如下--------");
//            for (int rol = 0; rol < maxRol; rol++) {
                XSSFRow row1 = sheet.getRow(row).getCell(0).getRow();
                XSSFCell cell = row1.getCell(1);
                cell.setCellValue("测试机");
//                System.out.print(sheet.getRow(row).getCell(rol) + " ");
//            }
//            System.out.println();
//        }
        return out.toByteArray();
    }

Excel复制行工具

/**
     * 行复制功能
     *
     * @param wb            工作簿
     * @param fromRow       从哪行开始
     * @param toRow         目标行
     * @param copyValueFlag true则连同cell的内容一起复制
     */
    public static void copyRow(Workbook wb, Row fromRow, Row toRow, boolean copyValueFlag) {
        toRow.setHeight(fromRow.getHeight());

        for (Iterator<Cell> cellIt = fromRow.cellIterator(); cellIt.hasNext(); ) {
            Cell tmpCell = cellIt.next();
            Cell newCell = toRow.createCell(tmpCell.getColumnIndex());
            copyCell(wb, tmpCell, newCell, copyValueFlag);
        }

        Sheet worksheet = fromRow.getSheet();

        for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {
            CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
            if (cellRangeAddress.getFirstRow() == fromRow.getRowNum()) {
                CellRangeAddress newCellRangeAddress = new CellRangeAddress(toRow.getRowNum(),
                        (toRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
                        cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
                worksheet.addMergedRegionUnsafe(newCellRangeAddress);
            }
        }
    }


    /**
     * 复制单元格
     *
     * @param srcCell
     * @param distCell
     * @param copyValueFlag true则连同cell的内容一起复制
     */
    public static void copyCell(Workbook wb, Cell srcCell, Cell distCell, boolean copyValueFlag) {
        CellStyle newStyle = wb.createCellStyle();
        CellStyle srcStyle = srcCell.getCellStyle();

        newStyle.cloneStyleFrom(srcStyle);
        newStyle.setFont(wb.getFontAt(srcStyle.getFontIndex()));

        // 样式
        distCell.setCellStyle(newStyle);

        // 内容
        if (srcCell.getCellComment() != null) {
            distCell.setCellComment(srcCell.getCellComment());
        }

        // 不同数据类型处理
        CellType srcCellType = srcCell.getCellTypeEnum();
        distCell.setCellType(srcCellType);

        if (copyValueFlag) {
            if (srcCellType == CellType.NUMERIC) {
                if (DateUtil.isCellDateFormatted(srcCell)) {
                    distCell.setCellValue(srcCell.getDateCellValue());
                } else {
                    distCell.setCellValue(srcCell.getNumericCellValue());
                }
            } else if (srcCellType == CellType.STRING) {
                distCell.setCellValue(srcCell.getRichStringCellValue());
            } else if (srcCellType == CellType.BLANK) {

            } else if (srcCellType == CellType.BOOLEAN) {
                distCell.setCellValue(srcCell.getBooleanCellValue());
            } else if (srcCellType == CellType.ERROR) {
                distCell.setCellErrorValue(srcCell.getErrorCellValue());
            } else if (srcCellType == CellType.FORMULA) {
                distCell.setCellFormula(srcCell.getCellFormula());
            }
        }

    }
public static void toDownload(byte[] bytes, String fileName) throws IOException {
        HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
        boolean isIE = isIE();
        if (isIE) {
            fileName = URLEncoder.encode(fileName, "UTF8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }

        resp.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        Cookie cookie = new Cookie(FILEDOWNLOAD, "true");
        cookie.setPath("/");
        resp.addCookie(cookie);
        OutputStream out = resp.getOutputStream();
        out.write(bytes);
        out.close();
    }
  public static ServletRequestAttributes getServletActionContext() {
    return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现根据页面选择的数据导出 Excel 文件,你可以按照以下步骤进行操作: 1. 在 JSP 页面中,创建一个表单或者其他方式让用户选择需要导出数据。例如,可以使用复选框或下拉菜单来让用户选择数据。 2. 当用户选择完数据并点击导出按钮时,提交表单或发送 AJAX 请求到后台。 3. 在后台的 JSP 或 Servlet 中,根据用户选择的数据,查询数据库或者获取相应的数据集合。 4. 使用 Apache POI(一个用于处理 Microsoft Office 文档的 Java 库)来创建 Excel 文件,并将查询到的数据填充到 Excel 中。 下面是一个简单的示例代码: ```java // 创建工作簿 Workbook workbook = new XSSFWorkbook(); // 创建工作表 Sheet sheet = workbook.createSheet("Sheet1"); // 创建标题行 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("列1"); headerRow.createCell(1).setCellValue("列2"); // ... // 填充数据行 int rowNum = 1; for (Data data : dataList) { // 假设dataList是你从数据库或其他地方获取的数据集合 Row dataRow = sheet.createRow(rowNum++); dataRow.createCell(0).setCellValue(data.getColumn1()); dataRow.createCell(1).setCellValue(data.getColumn2()); // ... } // 设置响应头信息 response.setHeader("Content-Disposition", "attachment; filename=\"data.xlsx\""); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 将工作簿写入响应输出流 try (OutputStream outputStream = response.getOutputStream()) { workbook.write(outputStream); } // 关闭工作簿 workbook.close(); ``` 注意,上面的代码只是一个示例,你需要根据你的具体需求进行适当的修改和调整。 5. 在页面JavaScript 中,处理后台返回的 Excel 文件数据,可以使用 Blob 对象和 URL.createObjectURL() 方法来生成下载链接,并触发下载操作。 ```javascript // 假设后台返回的 Excel 文件数据存在 response 变量中 var blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); var url = URL.createObjectURL(blob); var link = document.createElement('a'); link.href = url; link.download = 'data.xlsx'; link.click(); ``` 以上就是一个简单的示例,用于根据页面选择的数据导出 Excel 文件。你可以根据自己的需求进行相应的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值