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

java如何替換word/doc文件中的內(nèi)容

 更新時(shí)間:2023年06月30日 08:43:59   作者:五官一體即忢  
docx格式的文件本質(zhì)上是一個(gè)XML文件,只要用占位符在指定的地方標(biāo)記,然后替換掉標(biāo)記出的內(nèi)容,這篇文章主要介紹了java替換word/doc文件中的內(nèi)容,需要的朋友可以參考下

docx格式的文件本質(zhì)上是一個(gè)XML文件,只要用占位符在指定的地方標(biāo)記,然后替換掉標(biāo)記出的內(nèi)容,就能達(dá)到我們的目的

封裝成工具類

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
 * Author ht
 * Date: 2023-06-30
 */
//替換.docx文件的工具類
public class DocxUtil {
    //    保存隨機(jī)生的解壓出.docx文件的保存目錄
    private static final String cachePath = System.getProperty("user.dir") + File.separator + UUID.randomUUID().toString().replaceAll("-", "");
    //    保存模板文件的輸入流和模板壓縮輸入流
    private static final List<InputStream> iss = new ArrayList<>();
    //    替換docx文件中的內(nèi)容
    public static void compile(FileInputStream is, Map<String, String> data, FileOutputStream os) throws IOException {
//        獲取模板保存的目錄
        Path path = Paths.get(cachePath);
//        如果不存在或者當(dāng)前的模板輸入流不在輸入流集合中就解壓模板
        if (!Files.exists(path) || !iss.contains(is)) {
//        解壓docx文件
            unDocx(is);
        }
//        替換document.xml的內(nèi)容
        replaceXmlContent(data);
//        把解壓的文件重新壓縮成docx文件
        buildDocx(os);
    }
    //    解壓docx文件
    private static void unDocx(FileInputStream template) throws IOException {
//        解壓出來(lái)文件保存的目錄
        File cacheDir = new File(cachePath);
        if (!cacheDir.exists()) {
//            不存在就先創(chuàng)建該文件夾
            Files.createDirectory(Paths.get(cacheDir.getPath()));
        }
//        創(chuàng)建壓縮包輸入流
        ZipInputStream zis = new ZipInputStream(template);
//        把需要關(guān)閉的模板輸入流存到集合中
        iss.add(template);
        iss.add(zis);
//        獲取首個(gè)壓縮文件中的文件
        ZipEntry entry = zis.getNextEntry();
//        內(nèi)容緩沖區(qū)
        byte[] buff = new byte[1024 * 10];
//        循環(huán)獲取壓縮包中的壓縮文件
        while (entry != null) {
//            判斷當(dāng)前的壓縮文件是文件夾還是文件
            if (entry.isDirectory()) {
//                如果是文件夾就要?jiǎng)?chuàng)建對(duì)應(yīng)的文件夾
                Path tempDir = Paths.get(cacheDir.getPath() + File.separator + entry.getName());
//                不存在就創(chuàng)建
                if (!Files.exists(tempDir)) {
                    Files.createDirectory(tempDir);
                }
            } else {
//                如果是文件就創(chuàng)建文件寫(xiě)入內(nèi)容
                File file = new File(cacheDir, entry.getName());
//                創(chuàng)建文件的輸出流
                FileOutputStream fos = new FileOutputStream(file);
//                寫(xiě)入內(nèi)容到輸出流
                int len;
                while ((len = zis.read(buff)) != -1) {
                    fos.write(buff, 0, len);
                }
//                zis.transferTo(fos); // jdk9及更高版本可以用這個(gè)
//                關(guān)閉當(dāng)前文件的輸出流
                fos.close();
            }
//            獲取下一個(gè)壓縮文件
            entry = zis.getNextEntry();
        }
        System.out.println("===== 模板docx文件解壓完成 =====");
    }
    //    替換document.xml的內(nèi)容
    private static void replaceXmlContent(Map<String, String> data) throws IOException {
//        document.xml的位置
        String documentXmlPath = cachePath + File.separator + "word" + File.separator + "document.xml";
//        獲取document.xml文件的輸入流
        FileInputStream fis = new FileInputStream(documentXmlPath);
//        讀取xml中的內(nèi)容
        byte[] buff = new byte[fis.available()];
        fis.read(buff);
//        獲取xml文件中的內(nèi)容
        String content = new String(buff);
//        拿到Map集合中的數(shù)據(jù)和值,替換掉對(duì)應(yīng)位置的內(nèi)容
        for (String key : data.keySet()) {
            String value = data.get(key);
            System.out.println("替換 [ {{" + key + "}} ] 為 => [ " + value + " ]");
            content = content.replaceAll("\\{\\{" + key + "\\}\\}", value);
        }
//        把替換好的內(nèi)容寫(xiě)入原來(lái)的document.xml文件中
        FileOutputStream fos = new FileOutputStream(documentXmlPath);
//        寫(xiě)入內(nèi)容
        fos.write(content.getBytes(StandardCharsets.UTF_8));
//        關(guān)閉流
        fos.close();
        fis.close();
        System.out.println("===== 替換完成 =====");
    }
    //    把替換好document.xml內(nèi)容的文件夾重新壓縮成docx文件
    private static void buildDocx(FileOutputStream template) throws IOException {
//        創(chuàng)建壓縮文件輸出流
        ZipOutputStream zos = new ZipOutputStream(new DataOutputStream(template));
//        獲取要壓縮文件的路徑
        Path path = Paths.get(cachePath);
//        遍歷當(dāng)前壓縮文件路徑下的所有文件
        Files.walkFileTree(path, new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
//                獲取當(dāng)前文件的父目錄的名字
                String parent = file.getParent().getFileName().toString();
//                壓縮文件的名字
                String zipFileName;
//                如果父目錄是根目錄名字就是當(dāng)前的名字否則就是夫目錄加上當(dāng)前的名字
                if (parent.equals(path.toFile().getName())) {
                    zipFileName = file.toFile().getName();
                } else {
//                    如果父目錄的夫目錄是word就需要word+當(dāng)前文件的父目錄+當(dāng)前文件的名字
                    if ("word".equals(file.getParent().getParent().toFile().getName())) {
                        zipFileName = "word" + File.separator + parent + File.separator + file.toFile().getName();
                    } else {
//                        如果不是就是當(dāng)前文件的父目錄+當(dāng)前文件的名字
                        zipFileName = parent + File.separator + file.toFile().getName();
                    }
                }
//                把文件添加到壓縮包中
                zos.putNextEntry(new ZipEntry(zipFileName));
//                獲取當(dāng)前文件的輸入流
                DataInputStream zis = new DataInputStream(new FileInputStream(file.toFile()));
//                寫(xiě)入內(nèi)容到當(dāng)前的壓縮文件
                int len;
                byte[] buff = new byte[1024 * 10];
                while ((len = zis.read(buff)) != -1) {
                    zos.write(buff, 0, len);
                }
                zis.close();
//                zis.transferTo(zos); // jdk9及更高版本可以用這個(gè)
                return super.visitFile(file, attrs);
            }
        });
//        關(guān)閉流
        zos.close();
        template.close();
        System.out.println("===== 把解壓的文件重新壓縮成.docx ====");
    }
    //    關(guān)閉模板輸入流和清除緩存文件
    public static void closeTemplateAndClearCache() {
//        關(guān)閉集合中的所有流
        for (InputStream inputStream : iss) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //            刪除緩存文件
        deleteCache(new File(cachePath));
        System.out.println("===== 關(guān)閉了模板,清理了緩存 =====");
    }
    //    刪除不用的緩存解壓文件目錄
    private static void deleteCache(File cachePath) {
//        先刪文件夾里面的文件
        for (File file : Objects.requireNonNull(cachePath.listFiles())) {
//            是文件夾就遞歸調(diào)用
            if (file.isDirectory()) {
                deleteCache(file);
            } else {
//                是文件就直接刪
                file.delete();
            }
        }
//        刪掉自己
        cachePath.delete();
    }
}

使用

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * Author ht
 * Date: 2023-06-30
 */
public class App {
    public static void main(String[] args) throws IOException {
//        填充的數(shù)據(jù)
        Map<String, String> data = new HashMap<>();
        data.put("name", "hello world");
        data.put("time", "2022年10月1日");
//        模板輸入流
        FileInputStream is = new FileInputStream("src/main/resources/one.docx");
//        模板輸出流
        FileOutputStream os = new FileOutputStream("src/main/resources/test1.docx");
        FileOutputStream os1 = new FileOutputStream("src/main/resources/test2.docx");
//        生成模板
        DocxUtil.compile(is, data, os);
        DocxUtil.compile(is, data, os1);
        //    關(guān)閉模板輸入流和清除緩存文件
        DocxUtil.closeTemplateAndClearCache();
    }
}

記錄一些代碼和問(wèn)題處理方式,需要參考的請(qǐng)謹(jǐn)慎。

到此這篇關(guān)于java如何替換word/doc文件中的內(nèi)容的文章就介紹到這了,更多相關(guān)java替換文件內(nèi)容內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java中的FileWriter用法詳解與實(shí)戰(zhàn)記錄

    Java中的FileWriter用法詳解與實(shí)戰(zhàn)記錄

    這篇文章主要給大家介紹了關(guān)于Java中FileWriter用法的相關(guān)資料,包括寫(xiě)入字符數(shù)據(jù)到文件、字符數(shù)組和部分字符寫(xiě)入、配合BufferedWriter使用等方法,同時(shí)也解釋了其與OutputStreamWriter,BufferedWriter的異同特性,適合簡(jiǎn)單的文件寫(xiě)入操作,需要的朋友可以參考下
    2024-10-10
  • 如何在Java中使用標(biāo)準(zhǔn)庫(kù)創(chuàng)建臨時(shí)文件

    如何在Java中使用標(biāo)準(zhǔn)庫(kù)創(chuàng)建臨時(shí)文件

    有時(shí)候我們程序運(yùn)行時(shí)需要產(chǎn)生中間文件,但是這些文件只是臨時(shí)用途,并不做長(zhǎng)久保存,我們可以使用臨時(shí)文件,不需要長(zhǎng)久保存,這篇文章主要給大家介紹了關(guān)于如何在Java中使用標(biāo)準(zhǔn)庫(kù)創(chuàng)建臨時(shí)文件的相關(guān)資料,需要的朋友可以參考下
    2023-10-10
  • java模擬post請(qǐng)求登錄貓撲示例分享

    java模擬post請(qǐng)求登錄貓撲示例分享

    這篇文章主要介紹了java模擬post請(qǐng)求登錄貓撲的小示例,需要的朋友可以參考下
    2014-02-02
  • MyBatis-Plus3.x版本使用入門和踩過(guò)的坑

    MyBatis-Plus3.x版本使用入門和踩過(guò)的坑

    Mybatis-Plus是Mybatis的增強(qiáng)版,他只是在Mybatis的基礎(chǔ)上增加了功能,且并未對(duì)原有功能進(jìn)行任何的改動(dòng),本文給大家說(shuō)一下MyBatis-Plus3.x版本使用入門和踩過(guò)的坑,感興趣的朋友跟隨小編一起看看吧
    2023-10-10
  • Java批量導(dǎo)出word壓縮后的zip文件案例

    Java批量導(dǎo)出word壓縮后的zip文件案例

    這篇文章主要介紹了Java批量導(dǎo)出word壓縮后的zip文件案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-10-10
  • Spring Boot項(xiàng)目中Maven編譯參數(shù)source、target與release的區(qū)別及配置實(shí)踐方案

    Spring Boot項(xiàng)目中Maven編譯參數(shù)source、target與release的區(qū)別及配置實(shí)踐方案

    在Spring Boot項(xiàng)目開(kāi)發(fā)中,將本地代碼打包部署到服務(wù)器時(shí),常會(huì)遇到UnsupportedClassVersionError或NoSuchMethodError等異常,本文將直觀解析這些配置的區(qū)別,并提供標(biāo)準(zhǔn)的配置方案,感興趣的朋友跟隨小編一起看看吧
    2026-02-02
  • SpringBoot Session接口驗(yàn)證實(shí)現(xiàn)流程詳解

    SpringBoot Session接口驗(yàn)證實(shí)現(xiàn)流程詳解

    這篇文章主要介紹了SpringBoot+Session實(shí)現(xiàn)接口驗(yàn)證(過(guò)濾器+攔截器)文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-09-09
  • JpaRepository?實(shí)現(xiàn)簡(jiǎn)單條件查詢

    JpaRepository?實(shí)現(xiàn)簡(jiǎn)單條件查詢

    這篇文章主要介紹了JpaRepository?實(shí)現(xiàn)簡(jiǎn)單條件查詢,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • spring cloud oauth2 feign 遇到的坑及解決

    spring cloud oauth2 feign 遇到的坑及解決

    這篇文章主要介紹了spring cloud oauth2 feign 遇到的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • 詳解SpringBoot項(xiàng)目整合Vue做一個(gè)完整的用戶注冊(cè)功能

    詳解SpringBoot項(xiàng)目整合Vue做一個(gè)完整的用戶注冊(cè)功能

    本文主要介紹了SpringBoot項(xiàng)目整合Vue做一個(gè)完整的用戶注冊(cè)功能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07

最新評(píng)論

灵石县| 莱阳市| 丰镇市| 盈江县| 平阴县| 鄱阳县| 泰顺县| 新邵县| 临安市| 绥芬河市| 册亨县| 易门县| 湘潭县| 梧州市| 伊春市| 个旧市| 光山县| 岳阳县| 女性| 武隆县| 凉山| 江北区| 锡林浩特市| 聂拉木县| 建宁县| 许昌县| 民和| 昌邑市| 景德镇市| 防城港市| 万全县| 龙游县| 涿州市| 苍山县| 崇阳县| 沈丘县| 凤冈县| 黄石市| 客服| 荆州市| 虹口区|