Java 使用EasyExcel模板填充并將其轉(zhuǎn)換為PDF文件

最近公司有需求,需要實現(xiàn)數(shù)據(jù)打印功能船响。需要將數(shù)據(jù)填充到對應的模板文件數(shù)據(jù)膜宋,并將excel轉(zhuǎn)成pdf流傳給前端。其中呢數(shù)據(jù)的渲染使用了 easyexcel 做个,轉(zhuǎn)pdf使用到了Free Spire.Xls for Java 產(chǎn)品(免費java 組件)

基于excel模板填充數(shù)據(jù)

poi-tl 是一個Word 模板引擎鸽心,基于 Microsoft Word 模板和數(shù)據(jù)生成新的文檔腔呜,并且支持用戶自定義函數(shù),函數(shù)可以在 Word 模板的任何位置執(zhí)行再悼。

導入依賴:

                    <!-- easyexcel -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.2.1</version>
        </dependency>

<!-- POI導入導出 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

具體的使用可以去查相關的文檔核畴,比較簡單,只需定義要你的模板冲九,查詢對應的數(shù)據(jù)出來

2谤草、Excel轉(zhuǎn)pdf

使用Free Spire.xls for Java 工具
對應文檔鏈接:https://www.e-iceblue.cn/Downloads/Free-Spire-XLS-JAVA.html

導入依賴:
可以通過maven倉庫安裝,也可以自行下載安裝

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>


<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

示例:

public static void main(String[] args) {

           //創(chuàng)建Workbook 實例并加載示例文檔
            Workbook workbook = new Workbook();
            workbook.loadFromHtml(filePath);
            //轉(zhuǎn)換時設置工作表適應寬度
            workbook.getConverterSetting().setSheetFitToWidth(true);
            //轉(zhuǎn)換時設置工作表適應頁面
            workbook.getConverterSetting().setSheetFitToPage(true);
            //保存為PDF文檔格式
            document.saveToFile("D://最終委托書.pdf", FileFormat.PDF);

}

以下是對應開發(fā)的接口代碼如下:

    @ApiOperation(value = "服務委托書模板")
    @GetMapping(value = "/exportServiceBook/{id}")
    public void exportMyArchiveList(HttpServletResponse response, @PathVariable("id") String id, Date createTime) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("服務委托書", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //獲取需要導出的數(shù)據(jù)
        MtOrderExportInfo exportInfo = mtOrderTimeService.selectExportInfo(id, createTime, SecurityUtils.getGroupId(), SecurityUtils.getUserId());
        //獲取模板
        String FileName = "服務委托書.xlsx";
        String path = "D://服務委托書.xlsx";
        String filePath = "D://aaa_temp.xlsx";
        //URL url = new URL(path);
        //Resource resource = new UrlResource(url);
        try (InputStream inputStream = new FileInputStream(path);
             ServletOutputStream outputStream = response.getOutputStream()) {
            //設置輸出流和模板信息
            ExcelWriter excelWriter = EasyExcel.write(filePath).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(exportInfo, writeSheet);
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
          //定義兩個list導出
            List<MtOrderItemTimeExport> itemInfo = exportInfo.getItemInfoList();
            List<MtOrderItemTimeExport> goodsItemInfo = exportInfo.getGoodsItemInfoList();
            excelWriter.fill(new FillWrapper("itemInfo", itemInfo), fillConfig, writeSheet);
            excelWriter.fill(new FillWrapper("goodsItemInfo", goodsItemInfo), fillConfig, writeSheet);
            excelWriter.finish();
            //因為列表要循環(huán)多個 但是如果你excel有定義邊框樣式 他不會自己設置 所以需要手動設置邊框處理
            //如果項目/商品 有多行的話 需要手動進行列合并處理 
            if ((CollectionUtils.isNotEmpty(itemInfo) && itemInfo.size() > 1) || (CollectionUtils.isNotEmpty(goodsItemInfo) && goodsItemInfo.size() > 1)) {
                FileInputStream sheetInputStream = new FileInputStream(new File(filePath));
                //判斷要處理多少行
                int itemInfoSize = CollectionUtils.isNotEmpty(itemInfo) ? itemInfo.size() : 0;
                int goodsInfoSize = CollectionUtils.isNotEmpty(goodsItemInfo) ? goodsItemInfo.size() : 0;
                XSSFWorkbook workbook = new XSSFWorkbook(sheetInputStream);
                XSSFSheet sheet = workbook.getSheetAt(0);
                //處理項目內(nèi)容
                int itemStartRow = 19;
                for (int i = 1; i < itemInfoSize; i++) {
                    // 合并列
                    // 自適應列寬
                    sheet.autoSizeColumn(0);
                    sheet.addMergedRegion(new CellRangeAddress(itemStartRow, itemStartRow, 1, 5));
                    sheet.addMergedRegion(new CellRangeAddress(itemStartRow, itemStartRow, 6, 11));
                    sheet.addMergedRegion(new CellRangeAddress(itemStartRow, itemStartRow, 12, 15));
                    sheet.addMergedRegion(new CellRangeAddress(itemStartRow, itemStartRow, 16, 17));
                    RegionUtil.setBorderRight(BorderStyle.THIN, new CellRangeAddress(itemStartRow, itemStartRow, 16, 17), sheet);
                    RegionUtil.setBorderBottom(BorderStyle.THIN, new CellRangeAddress(itemStartRow, itemStartRow, 1, 17), sheet);
                    itemStartRow += 1;
                }
                //處理商品內(nèi)容
                int goodsStartRow = itemStartRow + 4;
                for (int i = 1; i < goodsInfoSize; i++) {
                    // 合并列
                    // 自適應列寬
                    sheet.autoSizeColumn(0);
                    sheet.addMergedRegion(new CellRangeAddress(goodsStartRow, goodsStartRow, 1, 3));
                    sheet.addMergedRegion(new CellRangeAddress(goodsStartRow, goodsStartRow, 4, 6));
                    sheet.addMergedRegion(new CellRangeAddress(goodsStartRow, goodsStartRow, 7, 9));
                    sheet.addMergedRegion(new CellRangeAddress(goodsStartRow, goodsStartRow, 10, 12));
                    sheet.addMergedRegion(new CellRangeAddress(goodsStartRow, goodsStartRow, 13, 15));
                    sheet.addMergedRegion(new CellRangeAddress(goodsStartRow, goodsStartRow, 16, 17));
                    RegionUtil.setBorderRight(BorderStyle.THIN, new CellRangeAddress(goodsStartRow, goodsStartRow, 16, 17), sheet);
                    RegionUtil.setBorderBottom(BorderStyle.THIN, new CellRangeAddress(goodsStartRow, goodsStartRow, 1, 17), sheet);
                    goodsStartRow += 1;
                }

                FileOutputStream newOutputStream = new FileOutputStream(filePath);
                workbook.write(newOutputStream);
                outputStream.flush();
            }
            //創(chuàng)建Workbook 實例并加載示例文檔
            Workbook workbook = new Workbook();
            workbook.loadFromHtml(filePath);
            //轉(zhuǎn)換時設置工作表適應寬度
            workbook.getConverterSetting().setSheetFitToWidth(true);
            //轉(zhuǎn)換時設置工作表適應頁面
            workbook.getConverterSetting().setSheetFitToPage(true);
            //保存為PDF文檔格式
            workbook.saveToStream(outputStream, FileFormat.PDF);
            //刪除生成的excel臨時文件
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

模板如圖:


image.png

最終效果:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末莺奸,一起剝皮案震驚了整個濱河市丑孩,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌灭贷,老刑警劉巖温学,帶你破解...
    沈念sama閱讀 216,692評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異甚疟,居然都是意外死亡仗岖,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評論 3 392
  • 文/潘曉璐 我一進店門览妖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來轧拄,“玉大人,你說我怎么就攤上這事讽膏¢莸纾” “怎么了?”我有些...
    開封第一講書人閱讀 162,995評論 0 353
  • 文/不壞的土叔 我叫張陵府树,是天一觀的道長俐末。 經(jīng)常有香客問我,道長奄侠,這世上最難降的妖魔是什么卓箫? 我笑而不...
    開封第一講書人閱讀 58,223評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮遭铺,結(jié)果婚禮上丽柿,老公的妹妹穿的比我還像新娘。我一直安慰自己魂挂,他們只是感情好甫题,可當我...
    茶點故事閱讀 67,245評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著涂召,像睡著了一般坠非。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上果正,一...
    開封第一講書人閱讀 51,208評論 1 299
  • 那天炎码,我揣著相機與錄音盟迟,去河邊找鬼。 笑死潦闲,一個胖子當著我的面吹牛攒菠,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播歉闰,決...
    沈念sama閱讀 40,091評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼辖众,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了和敬?” 一聲冷哼從身側(cè)響起凹炸,我...
    開封第一講書人閱讀 38,929評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎昼弟,沒想到半個月后啤它,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,346評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡舱痘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,570評論 2 333
  • 正文 我和宋清朗相戀三年变骡,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片衰粹。...
    茶點故事閱讀 39,739評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡锣光,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出铝耻,到底是詐尸還是另有隱情,我是刑警寧澤蹬刷,帶...
    沈念sama閱讀 35,437評論 5 344
  • 正文 年R本政府宣布瓢捉,位于F島的核電站,受9級特大地震影響办成,放射性物質(zhì)發(fā)生泄漏泡态。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,037評論 3 326
  • 文/蒙蒙 一迂卢、第九天 我趴在偏房一處隱蔽的房頂上張望某弦。 院中可真熱鬧,春花似錦而克、人聲如沸靶壮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽腾降。三九已至,卻和暖如春碎绎,著一層夾襖步出監(jiān)牢的瞬間螃壤,已是汗流浹背抗果。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留奸晴,地道東北人冤馏。 一個月前我還...
    沈念sama閱讀 47,760評論 2 369
  • 正文 我出身青樓,卻偏偏與公主長得像寄啼,于是被迫代替她去往敵國和親逮光。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,647評論 2 354

推薦閱讀更多精彩內(nèi)容