Java POI导出Word、Excel、Pdf文档(可在线预览PDF)

1、导入依赖Pom.xml

       
            org.apache.poi
            poi
            3.14
        


    org.apache.poi
    poi-ooxml
    3.14


    org.apache.poi
    poi-scratchpad
    3.17


    com.aspose
    aspose-words
    15.8.0


    cn.afterturn
    easypoi-base
    4.3.0

2、Controller 

    @ApiOperation(value = "免用箱申请保函,word")
    @GetMapping("/freeBoxApplication")
    @Log(title = "免用箱申请保函", businessType = BusinessType.EXPORT)
    public ReturnResult freeBoxApplication(HttpServletResponse response, @RequestParam("id") String id) {
        response.setCharacterEncoding("UTF-8");
        XWPFDocument xwpfDocument = null;
        try {
            String fileNameEncode = URLEncoder.encode("免用箱申请保函", "UTF-8");
            String fileName = URLDecoder.decode(fileNameEncode, "UTF-8");
            xwpfDocument = wordService.freeBoxApplication(Long.valueOf(id));
            response.setContentType("application/msword");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".docx");
            xwpfDocument.write(response.getOutputStream());
            return ReturnResult.success();
        } catch (Exception e) {
            return ReturnResult.error(e.getMessage());
        } finally {
            if (xwpfDocument != null) {
                try {
                    xwpfDocument.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "免用箱申请保函PDF")
    @GetMapping("/freeBoxApplicationPDF")
    @Log(title = "免用箱申请保函PDF", businessType = BusinessType.EXPORT)
    public ReturnResult freeBoxApplicationPDF(HttpServletResponse response, @RequestParam("id") String id,@RequestParam("isPreview") Boolean isPreview) {
//isPreview为true,表示在线预览PDF,不用下载

        InputStream is = null;
        response.setCharacterEncoding("UTF-8");
        try {
            String fileNameEncode = URLEncoder.encode("免用箱申请保函", "UTF-8");
            String fileName = URLDecoder.decode(fileNameEncode, "UTF-8");
            is = pdfService.freeBoxApplicationPDF(Long.valueOf(id), fileName,isPreview);
            response.setContentType("application/mspdf");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
          String downFileName = redisCache.getCacheObject("downFileName");
            redisCache.deleteObject("downFileName");
            response.setHeader("preview_file_path",  java.net.URLEncoder.encode(downFileName+".pdf", "UTF-8"));
            response.setHeader("isPreview",  isPreview.toString());
            response.setHeader("Access-Control-Expose-Headers", "preview_file_path,isPreview");//允许前端获取相应头

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
           
            if (!isPreview){//在线预览PDF,不用返回流
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
                toClient.write(buffer);
            }
            return ReturnResult.success();
        } catch (Exception e) {
            return ReturnResult.error(e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "货代单导出,xlsx")
    @GetMapping("/freightBill")
    @Log(title = "货代单导出", businessType = BusinessType.EXPORT)
    public ReturnResult freightBill(HttpServletResponse response, @RequestParam("id") String id) {
        response.setCharacterEncoding("UTF-8");
        Workbook workbook = null;
        try {
            workbook = excelService.freightBill(Long.valueOf(id));
            response.setContentType("application/vnd.ms-excel");
            workbook.write(response.getOutputStream());
            return ReturnResult.success();
        } catch (Exception e) {
            return ReturnResult.error(e.getMessage());
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 3、Service

a、pdfService

    public InputStream freeBoxApplicationPDF(Long id, String fileName,Boolean isPreview) throws Exception {
        XWPFDocument xwpfDocument = wordService.freeBoxApplication(id);
        InputStream is = Word2PDFUtil.wordToPdf(fileName + UUID.randomUUID(), xwpfDocument,isPreview);
        return is;
    }

b、wordService

    public XWPFDocument freeBoxApplication(Long id) throws Exception {
        //Map map = commonService.getMarineSpecialMap(id);
        Map map = new HashMap<>();
        map.put("aa",123);
        map.put("bb",456);

        XWPFDocument xwpfDocument = WordExportUtil.exportWord07("templates/免用箱申请保函.docx",map);
        return xwpfDocument;
    }
//模板文档放在\src\main\resources\templates

c、excelService

    public Workbook freightBill(Long id) throws ErrorMessageException {
        //Map map = commonService.getMarineSpecialMap(id); 
        Map map = new HashMap<>();
        map.put("aa",123);
        map.put("bb",456);

        TemplateExportParams templateExportParams = new TemplateExportParams("templates/货代单.xlsx");
        Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, map);
        return workbook;
    }
//模板文档放在\src\main\resources\templates

 4、Utils

package com.XXX.utils;

import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.ruoyi.common.core.redis.RedisCache;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.concurrent.TimeUnit;

@Component
public class Word2PDFUtil {
    @Autowired
    private static RedisCache redisCache;

    @Autowired
    public void setRedisCache(RedisCache redisCache) {
        Word2PDFUtil.redisCache = redisCache;
    }
    private static boolean license = false;
    private static String temDir = "/www/tempFile";

    private static final Logger logger = LoggerFactory.getLogger(Word2PDFUtil.class);

    //初始化
    static { 
        try {
            // license.xml放在src/main/resources文件夹下
//            InputStream is = Word2PDFUtil.class.getClassLoader().getResourceAsStream("license.xml");
//某次打成jar包后,读取不了license.xml,折中用下面的两行读取即可
            String filePath = System.getProperty("user.dir") + "/config/license.xml";
            InputStream is = new BufferedInputStream(new FileInputStream(filePath));

            License aposeLic = new License();
            aposeLic.setLicense(is);
            license = true;
        } catch (Exception e) {
            license = false;
            logger.error("License验证失败...");
            e.printStackTrace();
        }
    }

    public static InputStream wordToPdf(String fileName, XWPFDocument xwpfDocument,Boolean isPreview) throws Exception {
        FileOutputStream pdfos = null;
        InputStream pdfIs = null;
        File pdfFile = null;
        File wordFile = null;
        try {
            if (!temDir.endsWith("/")) {
                temDir = temDir + File.separator;
            }
            File dir = new File(temDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String tmpPath = temDir + fileName;

            //将文件路径存入Redis中,方便预览读取
            redisCache.setCacheObject("downFileName",fileName,600, TimeUnit.SECONDS);

            //创建word空文件
            wordFile = new File(tmpPath + ".docx");
            FileOutputStream wos = new FileOutputStream(wordFile);
            //在word中写入模板+数据
            xwpfDocument.write(wos);
            wos.flush();
            wos.close();

            //生成一个空的PDF文件
            pdfFile = new File(tmpPath + ".pdf");
            pdfos = new FileOutputStream(pdfFile);
            if(temDir.equals("/www/tempFile")){
                FontSettings.setFontsFolder("/usr/share/fonts/dejavu",true);
            }
            //要转换的word文件
            Document doc = new Document(tmpPath + ".docx");
            //DocToPDF
            doc.save(pdfos, SaveFormat.PDF);

            //要返回的pdf文件流
            pdfIs = new FileInputStream(tmpPath + ".pdf");
        } finally {
            if (pdfos != null) {
                try {
                    pdfos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //删除临时文件
            if (wordFile.exists()){
                wordFile.delete();
            }
            if (pdfFile.exists() && !isPreview) {
                //暂不删除,用于预览查看
                pdfFile.delete();
            }
        }
        return pdfIs;
    }
}

5、模板截图

Java POI导出Word、Excel、Pdf文档(可在线预览PDF)_第1张图片

 Java POI导出Word、Excel、Pdf文档(可在线预览PDF)_第2张图片

6、前端

//接口js文件
import request from '@/utils/request'
export function feeConfirmTrackSheet(data) {
    return request({
        url: '/file/file/costConfirmation',
        responseType:'blob',
        method: 'get',
        params:data
    })
}




//导出方法的js文件
//需要导入js-file-download插件
import {
    feeConfirmTrackSheet
}
import fileDownload from "js-file-download";

export function downloadFile(customerName, processId, selectFileName, fileType , businessType = 0,isPreview) {

    //导出的文件名称
    const fileName = `${customerName}-${selectFileName}.${fileType}`

    //文件类型
    if (fileType === 'docx') {
        //模板的文件名称
        if (selectFileName === 'XXXXX文件') {

            //参数
            const data = {
                id: processId,
                customerName: customerName,
                type:businessType
            }

            //向后端传参取返回值,用插件处理
            feeConfirmTrackSheet(data).then(res => {
                fileDownload(res, fileName);
            })
        }else if (fileType === 'pdf') {
        if (selectFileName === 'XXXXX文件PDF') {
            const data = {
                id: processId,
                customerName: customerName,
                type:businessType,
                isPreview
            }
            feeConfirmTrackSheetPDF(data).then(res => {
                if (isPreview){
                    window.open("http://file.myguoli.cn/"+res, "_blank")
                } else {
                    fileDownload(res, fileName);
                }
            })
        }
}
}
}


//只需在HTML中调用downloadFile方法接口

你可能感兴趣的:(Java,java,word,excel)