多線程導出word

来源:https://www.cnblogs.com/heavenTang/archive/2023/03/08/17191304.html
-Advertisement-
Play Games

導出word,以下為導出單個和zip的兩種格式。 CountDownLatch運用 CountDownLatch和ExecutorService 線程池cachedThreadPool.submit 1、CountDownLatch 概念 CountDownLatch可以使一個獲多個線程等待其他線程 ...


導出word,以下為導出單個和zip的兩種格式。

CountDownLatch運用
CountDownLatch和ExecutorService 線程池cachedThreadPool.submit

1、CountDownLatch 概念

CountDownLatch可以使一個獲多個線程等待其他線程各自執行完畢後再執行。

CountDownLatch 定義了一個計數器,和一個阻塞隊列, 當計數器的值遞減為0之前,阻塞隊列裡面的線程處於掛起狀態,當計數器遞減到0時會喚醒阻塞隊列所有線程,這裡的計數器是一個標誌,可以表示一個任務一個線程,也可以表示一個倒計時器,
CountDownLatch可以解決那些一個或者多個線程在執行之前必須依賴於某些必要的前提業務先執行的場景。

點擊查看代碼

    @Override
    public void batchExportWord(PreDefenceApplyDto preDefenceApplyDto) {
        SystemUserInfo loginUser = AuthorityUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getUserId())) {
            throw new ServiceException(SimpleErrorCode.UserNotLogin);
        }
        if(StringUtils.isBlank(preDefenceApplyDto.getGrade())){
            throw new ServiceException(301,"請選擇年級");
        }
        String grade = preDefenceApplyDto.getGrade();
        List<String> collegeIds = preDefenceApplyDto.getCollegeIds();
        String majorId = preDefenceApplyDto.getMajorId();

        // 查詢學生論文結果
        List<String> studentIds = preDefenceApplyMapper.selectHasResStu(grade,collegeIds,majorId);
        if(CollectionUtils.isEmpty(studentIds)){
            throw new ServiceException(302,"暫無審核通過的學生可導出");
        }
        //學校名稱
        String schoolName = publicMapper.querySchoolName();

        FileOutputStream fileOutputStream = null;
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;

        String downloadName = "情況表.zip";
        response.setContentType("application/zip;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + Encodes.urlEncode(downloadName));
        String realPath = request.getSession().getServletContext().getRealPath("");

        try (
                OutputStream outputStream = response.getOutputStream();
                // 壓縮流
                ZipOutputStream zos = new ZipOutputStream(outputStream)){

                ExecutorService cachedThreadPool = Executors.newFixedThreadPool(studentIds.size());
                CountDownLatch latch = new CountDownLatch(studentIds.size());
                for(String stuId : studentIds){
                    cachedThreadPool.submit(() -> {
                        try {
                            zipPreWord(  bufferedInputStream, zos,
                                    stuId, schoolName ,realPath);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        latch.countDown();
                    });
                }
                cachedThreadPool.shutdown();
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void zipPreWord( BufferedInputStream bufferedInputStream,ZipOutputStream zos,
                           String studentId,String schoolName ,String realPath) throws IOException {


        byte[] buffer = new byte[1024];
        int len = 0;

        PreDefenceApplyVo preDefenceApplyVo = preDefenceApplyMapper.resultQuery(studentId);
        String fileName =studentId+preDefenceApplyVo.getStudentName();
        fileName=fileName.replaceAll("/", "-")+"情況表.doc";
        String filePath = realPath + File.separator + fileName;

        File outFile = new File(filePath );

        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

        Template template = null;
        try {
            template = configuration.getTemplate(schoolName + "情況表2.ftl"); 
        } catch (IOException e) {
            log.error("context", e);
            throw new ServiceException(SimpleErrorCode.ExecFailure);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("preDefenceApplyVo", preDefenceApplyVo);
        params.put("schoolName", schoolName);
        try {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));

            template.process(params, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        }


        ZipEntry zipEntry = new ZipEntry(fileName);
        bufferedInputStream = new BufferedInputStream( new FileInputStream(outFile));
        zos.putNextEntry(zipEntry);
        while ((len = bufferedInputStream.read(buffer)) != -1) {
            zos.write(buffer, 0, len);
        }

    }
    @Override
    public void exportWord(PreDefenceApplyDto preDefenceApplyDto) {
        SystemUserInfo loginUser = AuthorityUtil.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException(SimpleErrorCode.UserNotLogin);
        }
        String studentId = loginUser.getUserId();
        if (preDefenceApplyDto != null && StringUtils.isNotBlank(preDefenceApplyDto.getStudentId())) {
            studentId = preDefenceApplyDto.getStudentId();
        }
        //學校名稱
        String schoolName = publicMapper.querySchoolName();

        PreDefenceApplyVo preDefenceApplyVo = preDefenceApplyMapper.resultQuery(studentId);

        String fileName = schoolName + "情況表.doc";
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + stringToUnicode(fileName));

        String filePath = request.getSession().getServletContext().getRealPath("/");


        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

        Template template = null;
        try {
            template = configuration.getTemplate(schoolName + "情況表2.ftl"); 
        } catch (IOException e) {
            log.error("context", e);
            throw new ServiceException(SimpleErrorCode.ExecFailure);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("preDefenceApplyVo", preDefenceApplyVo);
        params.put("schoolName", schoolName);

        File outFile = new File(filePath + "/" + fileName);
        byte[] buffer = new byte[1024];
        int len = 0;
        BufferedInputStream bufferedInputStream = null;
        try {

            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));

            try {
                template.process(params, out);
            } catch (TemplateException e) {
                e.printStackTrace();
            }
            FileInputStream fileInputStream = new FileInputStream(outFile);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            out.close();
            fileInputStream.close();
            bufferedInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outFile.exists()) {
                if (!outFile.delete()) {
                    log.info("刪除失敗!");
                }
            }
        }

    }


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 前言 每次啟動SpringBoot項目時,總是能看到控制台列印了一串字元,隱約能辨認出是“Spring”,不知大家是否也好奇過是怎麼實現的,是直接列印固定的字元串,還是根據什麼演算法去生成的?於是閑暇無事,探究一番。 只想修改banner可以跳到文末查看 SpringBoot是怎麼列印的 Banner ...
  • 簡介 在現實世界中,我們常常需要等待其它任務完成,才能繼續執行下一步。Java實現等待子線程完成再繼續執行的方式很多。我們來一一查看一下。 Thread的join方法 該方法是Thread提供的方法,調用join()時,會阻塞主線程,等該Thread完成才會繼續執行,代碼如下: private st ...
  • 說起開源CMS,你會想到哪些呢?WordPress?DoraCMS?joomla? 今天再給大家推薦一個非常好用的開源CMS:Wagtail 如果您正在選型的話,可以瞭解一下Wagtail的特點: 基於Django構建,具有出色的文檔管理功能和友好的用戶界面。 提供了一個靈活且易於使用的頁面編輯器, ...
  • 學習網頁設計和網路編程可能是一種有趣而有意義的體驗,但需要時間,精力和練習.這裡有一些技巧可以幫助您更輕鬆地學習這些技能: 從基礎知識開始:在您深入研究高級主題之前,重要的是要有牢固的理解很重要基礎知識.首先學習HTML,CSS和JavaScript,這是網路的基礎語言. 使用線上資源:線上資源有許 ...
  • 概述 鎖是電腦協調多個進程或線程併發訪問某一資源的機制。在資料庫中,除傳統的計算資源(CPU、RAM、I/O)的爭用以外,數據也是一種供許多用戶共用的資源。如何保證數據併發訪問的一致性、有效性是所有資料庫必須解決的一個問題,鎖衝突也是影響資料庫併發訪問性能的一個重要因素。從這個角度來說,鎖對資料庫 ...
  • Java編程語言是由Sun微系統公司在20世紀90年代早期開發的。儘管Java主要用於基於internet的應用程式,但它是一種簡單、高效、通用的語言。Java最初是為運行在多個平臺上的嵌入式網路應用程式而設計的。它是一種可移植的、面向對象的解釋性語言。 Java是非常可移植的。相同的Java應用程 ...
  • VB.NET語言線上運行編譯,是一款可線上編程編輯器,在編輯器上輸入VB.NET語言代碼,點擊運行,可線上編譯運行VB.NET語言,VB.NET語言代碼線上運行調試,VB.NET語言線上編譯,可快速線上測試您的VB.NET語言代碼,線上編譯VB.NET語言代碼發現是否存在錯誤,如果代碼測試通過,將會 ...
  • 控制語句:程式預設是順序執行,但在實際項目中需要選擇、迴圈。 1 選擇控制語句if 1.1 if語句的形式 1 if(條件表達式) 2 {//複合語句,若幹條語句的集合 3 語句一; 4 語句二; 5 } 註意:如果條件成立執行大括弧里的所有語句,不成立的話大括弧里的語句都不執行。 if(條件表達式 ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...