Exportación de archivos Excel en Java

Use lo que la empresa ha aprendido como un ejemplo simple:
(La lógica de implementación simple es generar el archivo en el proyecto y eliminarlo nuevamente cuando el usuario lo descarga) El
siguiente programa es la configuración de propiedades, configuración de parámetros, configuración de datos, etc. de Excel en 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;
    }

El siguiente código es para configurar el estilo de la tabla de Excel, el llenado de datos y otras operaciones de procesamiento

        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;
    }

El siguiente es el evento de descarga del archivo

    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;
    }

El paquete Jar requerido en este artículo se puede descargar de Internet. Este artículo no proporciona los datos relevantes del paquete Jar. El proceso general se describe arriba. Si no se comprende el código, puede proporcionar ideas de referencia basadas en los comentarios.

Supongo que te gusta

Origin blog.csdn.net/FV8023/article/details/89711021
Recomendado
Clasificación