Java 导出 (动态导出,表头和Value动态获取)

项目上业务需求,导出数据为动态数据,没有固定表头,没有固定值,每个表单下导出得数据都不同,普通导出无法实现,下面我就给大家展示我得做法:

下面是我的Controller写法:

     注意的是:根据Hashmap获取不同数据在根据key value区分开,从新拼接,主要是看我的工具类,大家可以学习,希望能帮助你们‘

   /**
     * 表单导出
     * 
     * @param response
     * @param export
     * @param request
     */
    @RequestMapping("/fForm/toExportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map paramMap = RequestUtils.convertRequestToMap(request);
            Long formId = getLong(paramMap, "formId");
            // 姓名 手机号条件查询
            String condition = getString(paramMap, "condition");
            // 表头
            ArrayList excelHeader = new ArrayList();
            List> list1 = fFormService.findFFromFliedConfig(formId);
            excelHeader.add("序号");
            for (Map map : list1) {
                String showName = map.get("showName").toString();
                excelHeader.add(showName);
            }
            excelHeader.add("提交时间");
            String[] arrString = (String[]) excelHeader.toArray(new String[excelHeader.size()]);
            // 数据
            List> fromDataList = fFormService.findFFormData1(formId, condition);
            List dataList = new ArrayList();
            ArrayList datal = null;
            for (Map map : fromDataList) {
                datal = new ArrayList();
                datal.add(map.get("id").toString());
                if (map.get("sex") == null) {
                    map.put("sex", "");
                } else if (map.get("sex").equals("1")) {
                    map.put("sex", "男");
                } else if (map.get("sex").equals("2")) {
                    map.put("sex", "女");
                }
                for (Map map1 : list1) {
                    String dataName = String.valueOf(map1.get("dataName"));
                    String data = String.valueOf(map.get(dataName));
                    if (data == "null") {
                        datal.add("");
                    } else {
                        datal.add(data);
                    }
                }
                SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm :ss");
                datal.add(String.valueOf(s.format(map.get("commit_time"))));
                Object[] array = datal.toArray(new String[datal.size()]);
                dataList.add(array);
            }
            ExportExcel.exportExcel(request, response, "表单导出", arrString, dataList, "yyyy-MM-dd HH:mm :ss");
        } catch (

        Exception e) {
            e.printStackTrace();
        }
    }

导出工具类:

/**
 * 动态导出工具( 根据数据列动态获取集合中数据)
 * 
 * @author v_guoyunlong
 *
 */
public class ExportExcel {

    /**
     * 
     * 
     * @param fileName 文件名
     * @param headers 表格属性列名数组
     * @param dataset 需要显示的数据集合
     * @param pattern 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
     * @param file1
     * @param zc2
     * @param file
     * @param file
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
    public static HSSFWorkbook exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName,
            String[] headers, List dataset, String pattern) throws Exception {
        // 设置请求
        response.setHeader("content-disposition",
                String.format("attachment;filename*=utf-8'zh_cn'%s.xls", URLEncoder.encode(fileName, "utf-8")));
        response.setContentType("application/msexcel;charset=UTF-8");
        // 创建一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet("表单导出");
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据,产生数据行
        Iterator it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            // 从第1行开始创建
            row = sheet.createRow(index);
            Object[] obj = (Object[]) it.next();
            for (short i = 0; i < obj.length; i++) {
                HSSFCell cell = row.createCell(i);
                Object value = obj[i];
                String textValue = null;
                if (!"".equals(value) && value != null) {
                    if (value instanceof Integer) {
                        int intValue = (Integer) value;
                        cell.setCellValue(intValue);
                    } else if (value instanceof Float) {
                        float fValue = (Float) value;
                        cell.setCellValue(fValue);
                    } else if (value instanceof Double) {
                        double dValue = (Double) value;
                        cell.setCellValue(dValue);
                    } else if (value instanceof Long) {
                        long longValue = (Long) value;
                        cell.setCellValue(longValue);
                    } else if (value instanceof Date) {
                        Date date = (Date) value;
                        if (null == pattern || pattern.equals("")) {
                            pattern = "yyyy-MM-dd";
                        }
                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                        textValue = sdf.format(date);
                        cell.setCellValue(textValue);
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        textValue = value.toString();
                        // 设置单元格的值
                        cell.setCellValue(textValue);
                    }
                } else {
                    cell.setCellValue("");
                }
            }

        }

        OutputStream outputStream = response.getOutputStream();// 打开流
        // ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        // // 压缩包名
        // String fileNames = "表单压缩文件" + ".zip";
        // response.setContentType("application/octet-stream ");
        // // 表示不能用浏览器直接打开
        // response.setHeader("Connection", "close");
        // // 告诉客户端允许断点续传多线程连接下载
        // // response.setHeader("Accept-Ranges", "bytes");
        // response.setHeadear("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileNames, "utf-8"));
        // response.setCharacterEncoding("UTF-8");
        // // 创建一个zip实体
        // ZipEntry entry = new ZipEntry(fileName + ".xls");
        // zipOutputStream.putNextEntry(entry);
        // workbook.write(zipOutputStream);
        // // 刷新 关闭输出流
        // zipOutputStream.flush();
        // zipOutputStream.close();
        // 让列宽随着导出的列长自动适应
        for (int colNum = 0; colNum < headers.length; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                // 当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue() != null
                                ? currentCell.getStringCellValue().getBytes().length : 10;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            if (colNum == 0) {
                sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
            } else {
                sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
            }
        }
        // HSSFWorkbook写入流
        workbook.write(outputStream);
        // HSSFWorkbook关闭
        workbook.close();
        // 刷新流
        outputStream.flush();
        // 关闭流
        outputStream.close();
        return workbook;
    }

最后说的是,还是根据自己项目中的业务需求去写,工具类是通用,谢谢

你可能感兴趣的:(Java)