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

这篇具有很好参考价值的文章主要介绍了Java POI导出Word、Excel、Pdf文档(可在线预览PDF)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、导入依赖Pom.xml

       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.14</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>15.8.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.3.0</version>
</dependency>

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<String, Object> map = commonService.getMarineSpecialMap(id);
        Map<String,Integer> 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<String, Object> map = commonService.getMarineSpecialMap(id); 
        Map<String,Integer> 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、模板截图

poi文档,Java,java,word,excel

 poi文档,Java,java,word,excel

6、前端文章来源地址https://www.toymoban.com/news/detail-719442.html

//接口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 POI导出Word、Excel、Pdf文档(可在线预览PDF)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • vue在线预览word、excel、PDF

    1、安装依赖 如果是vue2.6版本或以下还需要额外安装 @vue/composition-api 2、预览WORD代码 3、预览EXCEL 4、预览PDF 5、项目参考地址

    2024年02月09日
    浏览(42)
  • java使用poi-tl导出word及转换PDF后的合并导出pdf

    为某单位开发的一款项目申报审批系统,用户需求在申报阶段填写的信息资料能够导出PDF。且项目申报的报告正文为用户上传,所以需要合并导出。 在项目初期阶段使用的是PDF的预设模板导出,因为以前使用过,比较熟悉。所以优先选择此方法,但项目测试阶段发现问题,因

    2024年02月06日
    浏览(60)
  • ios 实现PDF,Word,Excel等文档类型的读取与预览

    最近正在研发的项目有一个需求: 允许用户将iCloud中的文档上传,实现文件的流转。 以前接触的项目对于资料类的上传大多是仅限于图片与视频。对于文档类(PDF, Word, Excel, Text等), 因苹果的沙箱环境限制,想要读取文件是无法实现的。目前虽然可以支持选择文件,但只能通

    2024年02月06日
    浏览(29)
  • 前端(vue)js在线预览PDF、Word、Excel、ppt等office文件

    可选参数 pdf=true,word文档尝试以pdf方式显示,默认false watermark=水印文本,显示文本水印;“img:”+图片url表示图片水印,如:img:https://view.xdocin.com/demo/wm.png saveable=true,是否允许保存源文件,默认false printable=false,是否允许打印,默认true ©able=false,是否允许选择复制内容,

    2024年02月13日
    浏览(49)
  • web浏览器在线预览Excel,PDF,world文档解决方案

    众所周知啊,在web浏览器中是无法直接预览Excel、world文档等文件的,PDF有的浏览器是打开预览,有的浏览器是跳转到下载页,行为不一致也是让开发者头疼的事情。 今天给大家提供一个解决方案,实现office文件在线预览的解决方案,这个在开发OA,推送通知触达的应用非常有

    2024年02月17日
    浏览(44)
  • (Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出

    目录 1、引入jar包 2、pdf处理工具类 3、poi模板导出工具类 4、测试类 5、模板 6、最终效果  1、引入jar包   2、pdf处理工具类  3、poi模板导出工具类  4、测试类 5、模板 6、最终效果 

    2024年02月06日
    浏览(59)
  • Java实现Word文档转PDF,PDF转Word,PDF转Excel,PDF转换工具

    java实现word文档转PDF,PDF转word 解决只能转换4页问题 解决每页头部存在水印问题 引入依赖 破解的jar包 链接: https://pan.baidu.com/s/1MO8OBuf4FQ937R9KDtofPQ 提取码: 4tsn 源码路径:https://download.csdn.net/download/weixin_43992507/88215577 像流读取文件这些要关闭释放,不然异常报错文件的读取不会

    2024年02月13日
    浏览(29)
  • Java实现office办公文档在线预览(word、excel、ppt、txt等)

    文章目录 一、官网下载openOffice 安装包,运行安装(不同系统的安装请自行百度,这里不做过多描述) 二、pom中引入依赖 三、office文件转为pdf流的工具类 四、service层代码  五、controller层代码 office办公文档,如doc、docx、xls、xlsx、ppt、pptx是无法直接在浏览器中打开的,但很

    2024年02月11日
    浏览(37)
  • 前端实现文件预览(pdf、excel、word、图片)

    需求:实现一个在线预览pdf、excel、word、图片等文件的功能。 介绍:支持pdf、xlsx、docx、jpg、png、jpeg。 以下使用Vue3代码实现所有功能,建议以下的预览文件标签可以在外层包裹一层弹窗。 sandbox 这个属性如果是单纯预览图片可以不使用,该属性对呈现在 iframe 框架中的内容

    2024年02月10日
    浏览(42)
  • 记录--前端实现文件预览(pdf、excel、word、图片)

    需求:实现一个在线预览pdf、excel、word、图片等文件的功能。 介绍:支持pdf、xlsx、docx、jpg、png、jpeg。 以下使用Vue3代码实现所有功能,建议以下的预览文件标签可以在外层包裹一层弹窗。 iframe标签能够将另一个HTML页面嵌入到当前页面中,我们的图片也能够使用iframe标签来

    2024年02月09日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包