Excel转PDF,简单好上手,直接拿去用

话不多说, 直接上代码

1. 导入pom依赖

        <!--  pdf相关依赖  -->
        <dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>aspose-cells</artifactId>
            <version> 22.4</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.6</version>
        </dependency>

2. Controller

	@ApiOperation("导出数据信息Pdf")
    @Log(title = "数据信息", businessType = BusinessType.EXPORT)
    @GetMapping("/exportPdf")
    public void exportPdf(DataVo dataVo , HttpServletResponse response) {
        List<DataExceltVo> dataExcelVoList= dataService.selectList(dataVo);
        ExcelUtil.exportExcelPdf(dataExcelVoList, "数据信息", DataExceltVo.class, response);

    }

3. ExcelUtil



import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
 

/**
     * 导出excel
     *
     * @param list      导出数据集合
     * @param sheetName 工作表的名称
     * @return 结果
     */
    public static <T> void exportExcelPdf(List<T> list, String sheetName, Class<T> clazz, HttpServletResponse response) {
        try {
            String filename = encodingFilename(sheetName);
            response.reset();
            FileUtils.setAttachmentResponseHeader(response, filename);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            EasyExcel.write(os, clazz)
                .autoCloseStream(false)
                // 自动适配
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                // 大数值自动转换 防止失真
                .registerConverter(new ExcelBigNumberConvert())
                .sheet(sheetName).doWrite(list);

            ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
            XSSFWorkbook wb = new XSSFWorkbook(is);

            //设置输出格式
            response.reset();
            response.setContentType("application/pdf;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("statements.pdf", "utf-8"));
            OutputStream outputStream = response.getOutputStream();

            //转pdf输出
            ExcelUtil.toPdf(wb,outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException("导出Pdf异常");
        }
    }



/**
     * 转pdf
     *
     * @param wb           excel
     * @param outputStream 输出流
     */
    public static void toPdf(XSSFWorkbook wb, OutputStream outputStream) throws Exception {
        // 最后输出
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        Workbook we = new Workbook(is);
        //隐藏workbook中不需要的sheet页。
        printSheetPage(we, new int[]{0});
        //转pdf
        PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
        pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
        //写入 outputStream
        we.save(outputStream, pdfSaveOptions);
        is.close();
        os.close();
        wb.close();
    }




   /**
     * 获取license 去除水印
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = ExcelUtil.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


public static void printSheetPage(com.aspose.cells.Workbook wb, int[] page) {
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if (null == page || page.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
        } else {
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }


4. 将这个xml文件, 命名为License, 放在resources路径下

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
        sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值