导出功能详细代码

概述:该代码主要是根据业务需求开发完成的,后期如果需要用到可以自行修改代码

主要代码:

/**
     * @param type                           导出的文件类型
     * @param exportResourceCatalogueDetails 导出数据
     * @param response                       响应
     * @param request                        请求
     * @param versionIds                     传入的versionId参数
     */
    protected void export(String type, List<ExportResourceCatalogueDetail> exportResourceCatalogueDetails, HttpServletResponse response, HttpServletRequest request, List<Long> versionIds) {
        if (type.toUpperCase().equals(ExportTypeEnum.EXCEL.getReadableString())) {
            downLoadSourceExcel(response, "export" + ExcelTypeEnum.XLSX.getValue(), "数据资源目录信息",
                    exportResourceCatalogueDetails, ExportResourceCatalogueDetail.class);
        } else if (type.toUpperCase().equals(ExportTypeEnum.WORD.getReadableString())) {
            downLoadSourceWord(response, "export", "template.doc", exportResourceCatalogueDetails, request);
        } else if (type.toUpperCase().equals(ExportTypeEnum.ZIP.getReadableString())) {
            // 打成jar包路径不能直接通过request.getSession()访问
            String realPath = acquireJarPath();
            String parentPath = realPath + "table";

            try {
                parentPath = java.net.URLDecoder.decode(parentPath, "UTF-8");
            } catch (java.io.UnsupportedEncodingException ex) {
                log.error(ex.getLocalizedMessage());
            }

            File file = new File(parentPath);
            if (!file.exists()) {
                file.mkdir();
            }
            log.info("临时文件路径为:" + parentPath);

            DelAllFileUtil.delAllFile(parentPath);
            int i = 0;
            for (ExportResourceCatalogueDetail exportResourceCatalogueDetail : exportResourceCatalogueDetails) {
                getOneDoc(exportResourceCatalogueDetail, request, parentPath, versionIds.get(i++));
            }
            ZipExportUtil.zipExport(parentPath, response);

        } else {
            StringBuffer createSql = SqlExportUtils.getCreateSql(type, exportResourceCatalogueDetails, ExportResourceCatalogueDetail.class);
            if (type.toUpperCase().equals(ExportTypeEnum.MYSQL.getReadableString())) {
                SqlExportUtils.StringToSql(createSql.toString(), "mysql.sql", response);
            }
            if (type.toUpperCase().equals(ExportTypeEnum.PGSQL.getReadableString())) {
                SqlExportUtils.StringToSql(createSql.toString(), "pgsql.sql", response);
            }

        }
    }

导出Excel方法downLoadSourceExcel:

 /**
     * 下载excel文件
     * 临时,文件导出
     *
     * @param response
     * @param fileName 文件名
     */
    protected void downLoadSourceExcel(HttpServletResponse response, String fileName, String sheetName, List list, Class tClass) {
        try {
            log.info("start_downLoading");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("charset", "UTF-8");

            String encode = URLEncoder.encode("export.xlsx", StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment; filename=" + encode);

            response.setContentType("application/octet-stream");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.addHeader("Access-Control-Allow-Headers", "Content-Disposition");

            EasyExcel.write(response.getOutputStream(), tClass).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).excelType(ExcelTypeEnum.XLSX).sheet(sheetName).doWrite(list);
            log.info("end_downLoaded");
        } catch (IOException e) {
            log.error("Excel导出失败", e);
        }
    }

导出将多条数据导入同一个word中方法downLoadSourceWord:

主要使用WordExportUtil.exportWord07("doc/template.doc", docList)方法根据模板将数据导出并生成一个新的文件

  /**
     * 下载word文件(生成单个word文档,多个表格数据)
     * 临时,文件导出
     *
     * @param response
     * @param fileName 文件名
     */

    protected void downLoadSourceWord(HttpServletResponse response, String fileName, String modelName, List list, HttpServletRequest request) {
        try {
            log.info("start_downLoaded");

            List docList = new ArrayList();
            //准备数据,一个list对应一页doc的文档

            List<Map<String, Object>> maps = MapUtil.toListMap(list);
            for (Map<String, Object> map : maps) {
                docList.add(map);

            }
            //重置响应对象
            response.reset();
            // 指定下载的文件名--设置响应头
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + "export" + ".doc");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.addHeader("Access-Control-Allow-Headers", "Content-Disposition");

            XWPFDocument doc = WordExportUtil.exportWord07("doc/template.doc", docList);
            doc.write(response.getOutputStream());
            doc.close();
            log.info("end_downLoaded");
        } catch (Exception e) {
            log.error("Word导出失败", e);
        }
    }

导出单个word单个数据方法getOneDoc:

  /**
     * 根据数据目录信息导出单个文件(单个表格数据)
     *
     * @param user       保存数据的实体类
     * @param request    请求
     * @param parentPath 指定生成的临时文件路径
     */
    protected void getOneDoc(ExportResourceCatalogueDetail user, HttpServletRequest request, String parentPath, Long versionId) {

        try {
            log.info("start_downLoaded");

            List docList = new ArrayList();
            Map<String, Object> map = MapUtil.toMap(user);
            docList.add(map);

            String fileName = parentPath + "/" + versionId + ".docx";
            log.info("生成的文件路径为:" + fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);

            //读取模板,放置数据,然后从response获取输出流导出
            XWPFDocument doc = WordExportUtil.exportWord07("doc/template.doc", docList);
            doc.write(fileOutputStream);
            doc.close();
            log.info("end_downLoaded");
        } catch (Exception e) {
            log.error("Word导出失败", e);
        }
    }

获取jar包绝对路径方法:

  /**
     * 获取jar包中的绝对路径
     *
     * @return jar包中的绝对路径
     */
    protected String acquireJarPath() {
        //jar包编译后的相对路径
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
        //消除乱码
        try {
            path = java.net.URLDecoder.decode(path, "UTF-8");
        } catch (java.io.UnsupportedEncodingException ex) {
            log.error(ex.getLocalizedMessage());
        }
        //根据路径获取目标文件
        java.io.File jarFile = new java.io.File(path);
        //获取文件的绝对路径
        String jarFilepath = jarFile.getAbsolutePath();
        //输出内容://jarFilepath:  C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\file:\C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\cipher-client.jar!\BOOT-INF\classes!
        //我们需要得到 file 的上级目录
        int end = jarFilepath.indexOf("file");
        if (end > 0) {
            return jarFilepath.substring(0, end);
            //输出结果:C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\
        }
        return jarFilepath + "\\";
    }

导出zip的工具类:

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;

/**
 * zip打包下载工具
 *
 */
public class ZipExportUtil {
    /**
     * 打包
     * @param path 文件夹路径
     */
    public static void zipExport(String path, HttpServletResponse response){
        try {
            response.setContentType("application/DOWLOAD");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + ("export" + ".zip"));
            ServletOutputStream out = response.getOutputStream();
            toZip(path, out, true);
//            DelAllFileUtil.delAllFile("./src/main/resources/temporary");
        } catch (Exception e) {
            throw new RuntimeException( e.getMessage());
        }
    }
    /**
     * 打压缩包导出
     *
     * @param srcDir
     * @param out
     * @param keepDirStructure
     * @throws RuntimeException
     */
    public static void toZip(String srcDir, OutputStream out, boolean keepDirStructure) throws RuntimeException {
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), keepDirStructure);
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    throw new RuntimeException( e.getMessage());
                }
            }
        }
    }

    /**
     * 执行压缩
     *
     * @param sourceFile
     * @param zos
     * @param name
     * @param keepDirStructure
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean keepDirStructure)
            throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (keepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (keepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), keepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), keepDirStructure);
                    }
                }
            }
        }
    }
}

清空文件夹文件工具类:

import java.io.File;

/**
 * 删除服务器文件工具
 */
public class DelAllFileUtil {
    /**
     * 删除文件夹及子文件
     *
     * @param path 文件夹绝对路径
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 删除文件夹
     *
     * @param folderPath 文件夹绝对路径
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值