有关导出的一些方法-excel,word,pdf三种方法的导出

cotroller层

/**
     * 导出
     *
     * @param response
     * @param request
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping("exportMenace")
    public void exportMenace(HttpServletResponse response, HttpServletRequest request) throws IOException, NoSuchAlgorithmException {

        Params params = this.pageParam();
        Map paramMap = params.getMap();
        //导出类型:1-excel,2-word,3-pdf
        String export_type = (String) paramMap.get("export_type");
        if (!StringUtils.isEmpty(export_type)) {
            if (export_type.equals("1")) {
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment; filename="
                        + java.net.URLEncoder.encode("vul.csv", "UTF-8"));
                //查询漏洞结果
                List vulResult = riskService.exportMenace(paramMap);
                String[] header = {"整改状态", "IP地址", "端口", "威胁名称", "风险等级", "威胁来源", "威胁分类", "更新时间"};
                //  ExcelUtils.write(vulResultHead,vulResult,"vul_result",os,"vul_result.xlsx");
                CSVUtils.write(response.getOutputStream(), header, Constants.menaceResultHead, vulResult);
                this.getRequest().setAttribute("desc", MANUAL_SUBMIT_LOG + "我的威胁导出csv成功");
            } else if (export_type.equals("2")) {
                List<ExportMenceDTO> exportMenceDTOList = riskService.exportMenaceModel(paramMap);
                paramMap.put("listIntegrity", exportMenceDTOList);
                try {
                    WordFileUtils.createWord("提交威胁.doc", 2, paramMap, request, response);
                } catch (Exception e) {
                    logger.warning(e.getMessage());
                    this.getRequest().setAttribute("desc", MANUAL_SUBMIT_LOG + "提交漏动导出" + Constants.exportTypeMap.get(export_type) + "失败");
                }
                System.out.println("=======下载完成========");
            } else if (export_type.equals("3")) {
                List<ExportMenceDTO> exportMenceDTOList = riskService.exportMenaceModel(paramMap);
                paramMap.put("listIntegrity", exportMenceDTOList);
                try {
                    //生成临时word
                    File tempWordFile = WordFileUtils.createWordToPdf(2, paramMap);
                    PdfUtil.downloadDoc2pdf("提交威胁.pdf", tempWordFile, response);
                } catch (Exception e) {
                    logger.warning(e.getMessage());
                    this.getRequest().setAttribute("desc", MANUAL_SUBMIT_LOG + "提交漏动导出" + Constants.exportTypeMap.get(export_type) + "失败");
                }
                System.out.println("=======下载完成========");
            }
        }

    }

service层

public List<ExportMenceDTO> exportMenaceModel(Map map) throws IOException, NoSuchAlgorithmException {
        if (map.containsKey("ids")) {
            String ids = (String) map.get("ids");
            if (!StringUtils.isEmpty(ids)&&!ids.equals("")){
                List<Integer> idList = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
                map.put("ids",idList);
            }
        }
        List<ExportMenceDTO> exportMenceDTOList = menaceMapper.exportModel(map);
        if (exportMenceDTOList.size()>0){
            PageHandleAspect.setMenceModelPageName(exportMenceDTOList);
        }
        return exportMenceDTOList;
    }

引用的工具类

excel导出工具类:CSVUtils

package com.hhit.utils;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class CSVUtils {
    //    public static void main(String[] args) {
        FileInputStream fis=new FileInputStream(new File());
//    }
    private static final CSVFormat csvFormat = CSVFormat.DEFAULT;

    private CSVUtils() {
    }

    public static List<Map<String, Object>> read(InputStream is, Map<String, String> headerMap) throws IOException {
        String[] headers = headerMap.keySet().toArray(new String[0]);
        InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
        CSVParser parse = csvFormat.withHeader(headers).parse(isr);
        List<CSVRecord> records = parse.getRecords();
        records.remove(0);
        List<Map<String, Object>> result = new ArrayList<>();
        for (CSVRecord record : records) {
            Map<String, Object> column = new HashMap<>();
            for (String header : headers) {
                column.put(headerMap.get(header), record.get(header));
            }
            result.add(column);
        }
        parse.close();
        isr.close();
        return result;
    }

    public static void write(OutputStream os, Map<String, String> headerMap, List<Map<String, Object>> columnList) throws IOException {
        String[] headers = headerMap.keySet().toArray(new String[0]);
        OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
        osw.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
        CSVPrinter printer = csvFormat.withHeader(headers).print(osw);
        for (Map<String, Object> column : columnList) {
            List<Object> list = new ArrayList<>();
            for (String header : headers) {
                Object o = column.get(headerMap.get(header));
                if (o instanceof Date) {
                    o = DateUtils.parseDate((Date) o);
                }
                list.add(o);
            }
            printer.printRecord(list);
        }
        printer.flush();
        printer.close();
        osw.close();
    }

    public static void write(OutputStream os, String[] headers, Map<String, String> headerMap, List<Map<String, Object>> columnList) throws IOException {
        OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
        osw.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
        CSVPrinter printer = csvFormat.withHeader(headers).print(osw);
        for (Map<String, Object> column : columnList) {
            List<Object> list = new ArrayList<>();
            for (String header : headers) {
                Object o = column.get(headerMap.get(header));
                if (o instanceof Date) {
                    o = DateUtils.parseDate((Date) o);
                }
                list.add(o);
            }
            printer.printRecord(list);
        }
        printer.flush();
        printer.close();
        osw.close();
    }

    public static void setResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" +
                java.net.URLEncoder.encode(fileName, "UTF-8"));
    }
}

doc导出工具类:WordFileUtils

package com.hhit.utils;

import freemarker.core.XMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Value;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;


public class WordFileUtils {
    private static Configuration configuration = null;

    @Value("${vul.file.path}")
    private static String vulFilePath;

    public WordFileUtils() {
    }

    public static void createWord(String fileName,int exportType, Map<String, Object> dataMap, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        if (configuration == null) {
            configuration = new Configuration(Configuration.VERSION_2_3_28);
            configuration.setOutputFormat(XMLOutputFormat.INSTANCE);
            configuration.setDefaultEncoding("UTF-8");
            configuration.setClassicCompatible(true);
        }
        configuration.setClassForTemplateLoading(WordFileUtils.class, "/templates");//模板文件所在路径
        Template t;
        if (exportType == 1) {
            t = configuration.getTemplate("seep.ftl"); //获取模板文件
        } else {
            t = configuration.getTemplate("menace.ftl"); //获取模板文件
        }
        // 直接下载文件
        Writer out = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
        t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件
        out.close();
        download(fileName,outputStream, request, response);
        // 文件生成到目录

    }

    public static void download(String fileName,ByteArrayOutputStream byteArrayOutputStream, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/msword");
//        response.setHeader("Content-Disposition", "attachment; filename=" + new String("vulseep.doc".getBytes(),"UTF-8"));
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename="
                + java.net.URLEncoder.encode(fileName, "UTF-8"));
        response.setContentLength(byteArrayOutputStream.size());
        request.getSession();
        OutputStream outputstream = response.getOutputStream(); // 取得输出流
        byteArrayOutputStream.writeTo(outputstream); // 写到输出流
        byteArrayOutputStream.close(); // 关闭
        outputstream.flush(); // 刷数据
    }

    /**
     * 通过模板导出pdf文件
     *
     * @param data             数据
     * @param templateFileName 模板文件名
     * @throws Exception
     */
    public static ByteArrayOutputStream createPDF(Map<String, Object> data, String templateFileName) throws Exception {
        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        cfg.setClassForTemplateLoading(WordFileUtils.class, "/templates");
        ITextRenderer renderer = new ITextRenderer();
        OutputStream out = new ByteArrayOutputStream();
        try {
            // 设置 css中 的字体样式(暂时仅支持宋体和黑体) 必须,不然中文不显示
//            renderer.getFontResolver().addFont("/templates/font/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            // 设置模板的编码格式
            cfg.setEncoding(Locale.CHINA, "UTF-8");
            // 获取模板文件
            Template template = cfg.getTemplate(templateFileName, "UTF-8");
            StringWriter writer = new StringWriter();

            // 将数据输出到html中
            template.process(data, writer);
            writer.flush();

            String html = writer.toString();
            // 把html代码传入渲染器中
            renderer.setDocumentFromString(html);

            // 解决图片的相对路径问题 ##必须在设置document后再设置图片路径,不然不起作用
//            renderer.getSharedContext().setBaseURL("images/");
            renderer.layout();

            renderer.createPDF(out, false);
            renderer.finishPDF();
            out.flush();
            return (ByteArrayOutputStream) out;
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


    public static File createWordToPdf(int exportType, Map<String, Object> dataMap) throws Exception {
        File tempFile = createTempFile("docx");
        if (configuration == null) {
            configuration = new Configuration(Configuration.VERSION_2_3_28);
            configuration.setOutputFormat(XMLOutputFormat.INSTANCE);
            configuration.setDefaultEncoding("UTF-8");
            configuration.setClassicCompatible(true);
        }
        configuration.setClassForTemplateLoading(WordFileUtils.class, "/templates");//模板文件所在路径
        Template t;
        if (exportType == 1) {
            t = configuration.getTemplate("seep.ftl"); //获取模板文件
        } else {
            t = configuration.getTemplate("menace.ftl"); //获取模板文件
        }
        // 直接下载文件
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), StandardCharsets.UTF_8),
                10240);
        t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件
        out.close();
        return tempFile;
    }

    //-------------------------------------------------------pdf

    /**
     * 创建临时文件
     *
     * @param fileType
     * @return
     * @throws IOException
     */
    public static File createTempFile(String fileType) throws IOException {
        String tempFileName = UUID.randomUUID().toString().replace("-", "").toLowerCase();
//        File file = new File(vulFilePath);
        return File.createTempFile(tempFileName, "." + fileType);
    }


    /**
     * base64 写入到 FileOutputStream
     *
     * @param base64
     * @param fos
     * @return
     */
    public static boolean writeBase64ToFile(String base64, FileOutputStream fos) {
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            fos.write(bytes);
            fos.flush();
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


}

pdf导出工具类:PdfUtil

package com.hhit.utils;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.logging.Logger;

public class PdfUtil {
    private static final Logger logger = Logger.getLogger(PdfUtil.class.getName());

    private static boolean getLicense() {
        boolean result = false;
        try {
            // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
//通过下面直接配置licence路径更方便,路径可以当参数、或者配置在配置文件中,自行修改
//            InputStream is =  new FileInputStream("C:\\Users\\00\\Desktop\\baogao\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @param wordPath 需要被转换的word全路径带文件名
     * @param pdfPath  转换之后pdf的全路径带文件名
     */
    public static void doc2pdf(String wordPath, String pdfPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        try {
            long old = System.currentTimeMillis();
            File file = new File(pdfPath); //新建一个pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(wordPath); //Address是将要被转化的word文档
            doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            os.close();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
        } catch (Exception e) {
            logger.warning("apose-words 去水印验证失败!");
            e.printStackTrace();
        }
    }


    /**
     * @param tempWordFile 临时文件
     * @param response
     */
    public static void downloadDoc2pdf(String fileName,File tempWordFile, HttpServletResponse response) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        try {
            long old = System.currentTimeMillis();
            String wordPath = tempWordFile.getAbsolutePath();
            response.setContentType("application/pdf");
            //这里设置Credentials为true 也可以前端设置为false
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + java.net.URLEncoder.encode(fileName, "UTF-8"));
            Document doc = new Document(wordPath); //Address是将要被转化的word文档
            ServletOutputStream os = response.getOutputStream();
            doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            // 以流的形式下载文件。
            os.flush();
            os.close();
            tempWordFile.deleteOnExit();
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
        } catch (Exception e) {
            logger.warning("apose-words 转pdf失败!");
            e.printStackTrace();
        }
    }

}

以上只是后端代码,需要前端的传值才可以完成相关的功能

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值