Excel file export in Java

Use what the company has learned as a simple example:
(The simple implementation logic is to generate the file in the project, and delete the file again when the user downloads it) The
following program is the property configuration, parameter configuration, data configuration, etc. of Excel in Java

    public IResData exportGzrwqkaxmtjData(final IReqData req) throws SwordBaseCheckedException, IOException {
        final IResData res = new SwordRes();
        //获取窗体的值,引入实体类
        final Map<String, String> gzrwqkaxmtjForm = req.getFormData("gzrwqkaxmtjForm");
        //获取所需要导入Excel表中的数据
        final List<Map<String, Object>> information = (List<Map<String, Object>>) SwordServiceUtils.callService("DSJYPT.XMGL.GZRW.QKAXMTJ", gzrwqkaxmtjForm);
        //定义Excel中表格的数据格式
        final List<Map<String, Object>> excelList = new ArrayList<Map<String, Object>>();
        //定义Excel的相关信息
        final Map<String, Object> excel = new HashMap<String, Object>();
        excel.put("title", "标题名称");
        excel.put("sheet", "表名");
        //定义列名和列值
        final String[] columns = {"字段名"};
        final String[] fields = {"字段值"};
        excel.put("columns", columns);
        excel.put("fields", fields);
        excel.put("data", information);
        excelList.add(excel);
        final HSSFWorkbook workbook = new HSSFWorkbook();
        //处理数据,完成整体Excel的生成和设置
        this.exportExcel(workbook, excelList);
        //下面的代码功能为将文件生成放在项目中
        final String path = this.getHttpReq().getSession().getServletContext().getRealPath("路径");
        final String uuid = UUID.randomUUID().toString().replace("-", "");
        final FileOutputStream fos = new FileOutputStream(path + "/" + uuid + ".xls");
        workbook.write(fos);
        fos.flush();
        fos.close();
        res.addAttr("fileName", uuid);
        return res;
    }

The following code is to configure the Excel table style, data filling and other processing operations

        public HSSFWorkbook exportExcel(HSSFWorkbook workbook, List<Map<String, Object>> excelList) {
        for (Map<String, Object> excel : excelList) {
            int k = 0;
            final String sheetName = (String) excel.get("sheet");
            HSSFSheet sheet = null;
            if (GyUtils.isNull(sheetName)) {
                sheet = workbook.createSheet();
            } else {
                try {
                    sheet = workbook.createSheet(sheetName);
                } catch (Exception e) {
                    sheet = workbook.createSheet();
                }
            }
            final String title = (String) excel.get("title");
            final String[] columns = (String[]) excel.get("columns");
            //开始填入数据
            final String[] fields = (String[]) excel.get("fields");
            //设置标题
            if (!GyUtils.isNull(title)) {
                final HSSFCellStyle titleStyle = workbook.createCellStyle();
                final HSSFFont titleFont = workbook.createFont();
                titleFont.setFontName("黑体");
                titleFont.setFontHeightInPoints((short) 14);
                titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                titleStyle.setFont(titleFont);
                // 设置单元格格式居中
                titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                final int length = fields.length;
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, length - 1 >= 0 ? length - 1 : 0));
                final HSSFRow rowTitle = sheet.createRow(k);
                rowTitle.setHeight((short) (14 * 40));
                final HSSFCell cell = rowTitle.createCell(0);
                cell.setCellValue(title);
                cell.setCellStyle(titleStyle);
                k++;
            }
            final HSSFCellStyle cellStyle = workbook.createCellStyle();
            // 设置单元格格式居中
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            //设置标题
            if (!GyUtils.isNull(columns)) {
                final HSSFRow hssfRow = sheet.createRow(k);
                k++;
                for (int i = 0; i < columns.length; i++) {
                    final HSSFCell headCell = hssfRow.createCell(i);
                    headCell.setCellValue(columns[i]);
                    headCell.setCellStyle(cellStyle);
                    sheet.setColumnWidth(i, 80 * 80);
                }
            }
            //添加数据
            final List<?> listData = (List<?>) excel.get("data");
            for (Object vo : listData) {
                final HSSFRow row = sheet.createRow(k);
                k++;
                for (int j = 0; j < fields.length; j++) {
                    final HSSFCell headCell = row.createCell(j);
                    String value = "";
                    try {
                        value = GyUtils.getValueByKey(vo, fields[j]);
                    } catch (SwordBaseCheckedException e) {
                        value = "";
                    }
                    headCell.setCellValue(value);
                    headCell.setCellStyle(cellStyle);
                }
            }
        }
        return workbook;
    }

The following is the download event of the file

    public IResData downLoadFile(final IReqData req) throws SwordBaseCheckedException, IOException {
        final IResData res = new SwordRes();
        //获取到文件名
        final String fileName = (String) req.getAttr("fileName");
        //到指定路径下获取文件
        final File file = new File(this.getHttpReq().getSession().getServletContext().getRealPath("路径") + "/" + fileName + ".xls");
        //下载文件
        this.downLoad(file, "文件名.xls");
        //删除生成的文件
        file.delete();
        return res;
    }

The Jar package required in this article can be downloaded on the Internet. This article does not provide the relevant data of the jar package. The overall process is described above. If the code is not understood, you can provide reference ideas based on the comments.

Guess you like

Origin blog.csdn.net/FV8023/article/details/89711021