最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java如何向Word模板中插入Base64圖片和數(shù)據(jù)信息

 更新時(shí)間:2024年07月03日 08:41:44   作者:霽月清風(fēng)與誰同  
這篇文章主要介紹了Java如何向Word模板中插入Base64圖片和數(shù)據(jù)信息問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

需求

在服務(wù)端提前準(zhǔn)備好Word模板文件,并在用戶請(qǐng)求接口時(shí)服務(wù)端動(dòng)態(tài)獲取圖片。

數(shù)據(jù)等信息插入到模板當(dāng)中,然后返回包含數(shù)據(jù)信息的Word文件流。

一、準(zhǔn)備模板文件

在需要插入圖片的地方使用:{{@參數(shù)名}},文本信息使用:{{參數(shù)名}},進(jìn)行占位,占位格式將會(huì)被保留,經(jīng)過處理后格式不變

將準(zhǔn)備好的模板文件放在resources目錄下

blog.csdnimg.cn/direct/6d1474091083427483e11ea71e25ef51.png)

二、引入Poi-tl、Apache POI依賴

poi-tl(poi template language)是Word模板引擎,基于Apache POI,提供更友好的API,使用起來更加簡(jiǎn)單

版本對(duì)應(yīng)關(guān)系參考Poi-tl官網(wǎng)

<!--    替換自己使用的版本    -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.1.*</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.1.*</version>
</dependency>
<!--    Word模板引擎    -->
<dependency>
	<groupId>com.deepoove</groupId>
	<artifactId>poi-tl</artifactId>
	<version>1.7.*</version>
</dependency>

三、創(chuàng)建實(shí)體類(用于保存向Word中寫入的數(shù)據(jù))

參數(shù)名必須同Word模板中的參數(shù)名稱保持一致

import com.deepoove.poi.data.PictureRenderData;

@Data
public class DownloadDate {
    //圖片使用PictureRenderData類型
    private PictureRenderData image;
    private String name;
    private String a;
    private String b;
    private String c;
    private String d;
    private String e;
    private String f;
    private String g;
    private String h;
    private String i;
}

四、實(shí)現(xiàn)Service接口

public interface DownloadService {
     void download(HttpServletResponse response, DownloadDTO downloadDTO) throws IOException;
}
@Service
@Slf4j
public class DownloadServiceImpl implements DownloadService {

    @Resource
    //遠(yuǎn)程調(diào)用服務(wù)
    private FeignService feignService;
    
    @Override
    public void download(HttpServletResponse response, DownloadDTO downloadDTO) throws IOException {BufferedImage、字節(jié)數(shù)組),Base64可以轉(zhuǎn)字節(jié)數(shù)組后使用
    	//通過調(diào)用其它接口獲取待寫入的數(shù)據(jù)信息
    	WordData wordData = feignService.getData(downloadDTO);
        /** 
        * 圖片可以是多種格式------------------------
        * 圖片路徑:PictureRenderData(int width, int height, String path)
        * File:PictureRenderData(int width, int height, File picture)
        * InputStream:PictureRenderData(int width, int height, String format, InputStream input)
        * BufferedImage:PictureRenderData(int width, int height, String format, BufferedImage image)
        * 字節(jié)數(shù)組:PictureRenderData(int width, int height, String format, byte[] data)
        * Base64可以轉(zhuǎn)字節(jié)數(shù)組后使用
        */

        //以Base64為例,先獲取圖片的Base64編碼(wordData.getImg是原始圖片Base64數(shù)據(jù))
        String base64ImageData = wordData.getImg.substring(data.indexOf(",") + 1);
        //獲取圖片類型
        String format = getBase64Type(base64ImageData);
        // 將base64數(shù)據(jù)轉(zhuǎn)為字節(jié)數(shù)組
        byte[] imageBytes = Base64.getDecoder().decode(base64ImageData);
        // 將字節(jié)數(shù)組包裝成PictureRenderData
        PictureRenderData pictureRenderData = new PictureRenderData(690,530,format,imageBytes);
        //待寫入Word的數(shù)據(jù)
        DownloadDate downloadDate = new DownloadDate();
        //圖片信息
        downloadDate.setImage(pictureRenderData);
        //其它信息
        downloadDate.setName(wordData.getName());
        //...
        XWPFTemplate template = null;
        BufferedOutputStream bufferedOutputStream = null;
        ServletOutputStream outputStream = null;
        try {
        	/** 
        	* 該方法會(huì)導(dǎo)致在部分環(huán)境中資源找不到的情況,不推薦使用
        	*/
            //獲得resource路徑+模板路徑
            //String path = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).getPath() + "word/template.docx";
            // 讀取Word模板
            //FileInputStream templateInputStream = new FileInputStream(path);
            // 模板綁定數(shù)據(jù)
            //template = XWPFTemplate.compile(templateInputStream).render(imageDownloadDate);
            
            // 從資源中加載Word模板
            try (InputStream templateInputStream = getClass().getClassLoader().getResourceAsStream("word/template.docx")) {
                if (templateInputStream != null) {
                    // 模板綁定數(shù)據(jù)
                    template = XWPFTemplate.compile(templateInputStream).render(imageDownloadDate);
                } else {
                    // 處理模板資源未找到的情況
                    log.error("Word模板資源未找到");
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    return;
                }
            }
            //文件名
            String encodedFileName = URLEncoder.encode(System.currentTimeMillis()+"", "utf-8");
            //設(shè)置響應(yīng)信息
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName + ".docx");
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setCharacterEncoding("utf-8");
            outputStream = response.getOutputStream();
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            template.write(bufferedOutputStream);
            //清空流
            bufferedOutputStream.flush();
            outputStream.flush();
        } catch (Exception e) {
            log.info(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            //關(guān)閉資源
            PoitlIOUtils.closeQuietlyMulti(template, bufferedOutputStream, outputStream);
        }
    }
    
    //根據(jù)base64編碼獲取圖片格式信息
    private String getBase64Type(String base64) {
        byte[] b = Base64.getDecoder().decode(base64);
        String type = ".png";
        if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".bmp";
        } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".png";
        } else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".jpg";
        } else if (0x49492A00 == ((b[0] & 0xff) << 24 | (b[1] & 0xff) << 16 | (b[2] & 0xff) << 8 | (b[3] & 0xff))) {
            type = ".tif";
        }
        return type;
    }

}

五、Controller層實(shí)現(xiàn)

@RestController
@RequestMapping("/test")
@Api(tags = "獲取商品圖片")
public class GetImageController {

    @Resource
    DownloadService downloadService;

    @PostMapping("/download")
    @ApiOperation(value = "下載Word")
    void download(HttpServletResponse response,@RequestBody DownloadDTO downloadDTO) throws IOException {
        //鑒權(quán)或其它處理
        //....
        downloadService.download(response,downloadDTO);
    }
    
}

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。 

相關(guān)文章

  • Java調(diào)用新浪api通過Ip查詢地區(qū)

    Java調(diào)用新浪api通過Ip查詢地區(qū)

    這篇文章主要介紹了Java調(diào)用新浪接口通過Ip查詢地區(qū),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • Java數(shù)據(jù)結(jié)構(gòu)之圖(動(dòng)力節(jié)點(diǎn)Java學(xué)院整理)

    Java數(shù)據(jù)結(jié)構(gòu)之圖(動(dòng)力節(jié)點(diǎn)Java學(xué)院整理)

    本文章主要講解學(xué)習(xí)如何使用JAVA語言以鄰接表的方式實(shí)現(xiàn)了數(shù)據(jù)結(jié)構(gòu)---圖(Graph)。對(duì)java數(shù)據(jù)結(jié)構(gòu)之圖相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧
    2017-04-04
  • SpringBoot整合Quartz方法詳解

    SpringBoot整合Quartz方法詳解

    這篇文章詳解介紹了SpringBoot整合Quartz的方法,Quartz是一個(gè)比較成熟了的定時(shí)任務(wù)框架,本文實(shí)例代碼給大家詳細(xì)講解,需要的朋友可以參考下
    2023-04-04
  • 16進(jìn)制顯示字節(jié)流技巧分享

    16進(jìn)制顯示字節(jié)流技巧分享

    這篇文章主要介紹了16進(jìn)制顯示字節(jié)流的技巧分享,需要的朋友可以參考下
    2014-02-02
  • IDEA項(xiàng)目maven?project沒有出現(xiàn)plugins和Dependencies問題

    IDEA項(xiàng)目maven?project沒有出現(xiàn)plugins和Dependencies問題

    這篇文章主要介紹了IDEA項(xiàng)目maven?project沒有出現(xiàn)plugins和Dependencies問題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • Netty分布式固定長(zhǎng)度解碼器實(shí)現(xiàn)原理剖析

    Netty分布式固定長(zhǎng)度解碼器實(shí)現(xiàn)原理剖析

    這篇文章主要為大家介紹了Netty分布式固定長(zhǎng)度解碼器原理剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-03-03
  • 淺談Java中Lock和Synchronized的區(qū)別

    淺談Java中Lock和Synchronized的區(qū)別

    這篇文章主要介紹了Java中Lock和Synchronized的區(qū)別,Lock和Synchronized都是java中去用來解決線程安全問題的一個(gè)工具,但是具體有什么區(qū)別呢?下面我們一起進(jìn)入文章了解具體詳細(xì)內(nèi)容吧,需要的朋友可以參考一下
    2022-04-04
  • Mybatis-Plus通用枚舉的使用詳解

    Mybatis-Plus通用枚舉的使用詳解

    這篇文章主要介紹了Mybatis-Plus通用枚舉的使用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Java Apollo環(huán)境搭建以及集成SpringBoot案例詳解

    Java Apollo環(huán)境搭建以及集成SpringBoot案例詳解

    這篇文章主要介紹了Java Apollo環(huán)境搭建以及集成SpringBoot案例詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • volatile與happens-before的關(guān)系與內(nèi)存一致性錯(cuò)誤

    volatile與happens-before的關(guān)系與內(nèi)存一致性錯(cuò)誤

    本文講了Java并發(fā)編程中volatile變量、happens-before與內(nèi)存一致性錯(cuò)誤,下面來和小編一起學(xué)習(xí)下如何解決
    2019-05-05

最新評(píng)論

大同县| 会泽县| 阿尔山市| 二连浩特市| 扎囊县| 龙门县| 苍南县| 青铜峡市| 咸宁市| 桃园市| 广东省| 凤台县| 文昌市| 攀枝花市| 昆山市| 黄石市| 南阳市| 电白县| 大方县| 孝感市| 随州市| 北宁市| 盘锦市| 马公市| 堆龙德庆县| 东海县| 晋州市| 富源县| 集安市| 定边县| 枣阳市| 垣曲县| 南华县| 陵水| 汉阴县| 长宁区| 广元市| 凉山| 宣化县| 鹰潭市| 郴州市|