国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

easyExcel合并單元格導(dǎo)出

這篇具有很好參考價(jià)值的文章主要介紹了easyExcel合并單元格導(dǎo)出。希望對大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

效果圖

easyExcel合并單元格導(dǎo)出,SpringBoot,spring boot,java,easyExcel

一、導(dǎo)入maven依賴

(很多舊項(xiàng)目自定義了一套Excel導(dǎo)出工具,poi版本可能不兼容,一般poi新舊版本不兼容分界線在3.17,選擇3.17版本不會(huì)發(fā)生代碼不兼容情況)文章來源地址http://www.zghlxwxcb.cn/news/detail-705255.html

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.6</version>
            <exclusions>

                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi-ooxml</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi-ooxml-schemas</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
            <classifier>sources</classifier>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>

二、重寫easyExcel-自定義寫入處理器


import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定義合并策略 該類繼承了AbstractMergeStrategy抽象合并策略,需要重寫merge()方法
 * @author reshui
 * @date 2023/9/4
 **/
public class CustomMergeStrategy extends AbstractMergeStrategy {

    /**
     * 分組,每幾行合并一次
     */
    private List<Integer> exportFieldGroupCountList;

    /**
     * 目標(biāo)合并列index
     */
    private Integer targetColumnIndex;

    /**
     * 需要開始合并單元格的首行index
     */
    private Integer rowIndex;

    /**
     * @param exportDataList exportDataList為待合并目標(biāo)列的值
     * @param targetColumnIndex 需要合并的列
     * @return {@code  }
     * @author reshui
     * @date 2023/09/05
     */
    public CustomMergeStrategy(List<String> exportDataList, Integer targetColumnIndex) {
        this.exportFieldGroupCountList = getGroupCountList(exportDataList);
        this.targetColumnIndex = targetColumnIndex;
    }


    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
        if (null == rowIndex) {
            rowIndex = cell.getRowIndex();
        }
        // 僅從首行以及目標(biāo)列的單元格開始合并,忽略其他
        if (cell.getRowIndex() == rowIndex && cell.getColumnIndex() == targetColumnIndex) {
            mergeGroupColumn(sheet);
        }
    }

    private void mergeGroupColumn(Sheet sheet) {
        int rowCount = rowIndex;
        for (Integer count : exportFieldGroupCountList) {
            if (count == 1) {
                rowCount += count;
                continue;
            }
            // 合并單元格
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount + count - 1, targetColumnIndex, targetColumnIndex);
            sheet.addMergedRegionUnsafe(cellRangeAddress);
            rowCount += count;
        }
    }

    /**
     * 該方法將目標(biāo)列根據(jù)值是否相同連續(xù)可合并,存儲(chǔ)可合并的行數(shù)
     * @param exportDataList
     * @return {@code List<Integer> }
     * @author reshui
     * @date 2023/09/05
     */
    private List<Integer> getGroupCountList(List<String> exportDataList) {
        if (CollectionUtils.isEmpty(exportDataList)) {
            return new ArrayList<>();
        }

        List<Integer> groupCountList = new ArrayList<>();
        int count = 1;

        for (int i = 1; i < exportDataList.size(); i++) {
            if (exportDataList.get(i).equals(exportDataList.get(i - 1))) {
                count++;
            } else {
                groupCountList.add(count);
                count = 1;
            }
        }
        // 處理完最后一條后
        groupCountList.add(count);
        return groupCountList;
    }


}

三、導(dǎo)出工具類封裝



import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;



/**
 * 下載excel文件工具
 *
 * @author reshui
 * @date 2023/09/05
 */
public class DownloadExcelUtil {

    private static final Logger log = LoggerFactory.getLogger(DownloadExcelUtil.class);

    private final static String separatorChar = "-";

    public static <T> void downloadFile(HttpServletResponse response, Class<T> clazz, String data) throws IOException {
        String timeStamp = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        String fileName = timeStamp + "-log";
        downloadFile(response, clazz, data, fileName, "數(shù)據(jù)", null);
    }

    /**
     * @param response         響應(yīng)請求
     * @param clazz            導(dǎo)出數(shù)據(jù)類型
     * @param data             數(shù)據(jù)源
     * @param customFileName   文件名
     * @param sheetName        頁名
     * @param writeHandlerList 自定義寫入處理器
     * @return {@code T }
     * @author reshui
     * @date 2023/09/05
     */
    public static <T> T downloadFile(HttpServletResponse response, Class<T> clazz
            , String data
            , String customFileName
            , String sheetName
            , List<WriteHandler> writeHandlerList) throws IOException {
        // 這里注意 有同學(xué)反應(yīng)使用swagger 會(huì)導(dǎo)致各種問題,請直接用瀏覽器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 這里URLEncoder.encode可以防止中文亂碼 當(dāng)然和easy-excel沒有關(guān)系
            String fileName = URLEncoder.encode(customFileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 這里需要設(shè)置不關(guān)閉流
            ExcelWriterSheetBuilder writerSheetBuilder = EasyExcel.write(response.getOutputStream(), clazz).autoCloseStream(Boolean.FALSE).sheet(sheetName);
            if (CollUtil.isNotEmpty(writeHandlerList)) {
                for (WriteHandler writeHandler : writeHandlerList) {
                    writerSheetBuilder.registerWriteHandler(writeHandler);
                }
            }
            writerSheetBuilder.doWrite(JSONObject.parseArray(data, clazz));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>(2);
            map.put("status", "failure");
            map.put("message", "下載文件失敗" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
        return null;
    }




    /**
     * 出把excel
     *
     * @param timeStamp       時(shí)間戳
     * @param excelFileName   excel文件名字
     * @param headClassType   頭類類型
     * @param resultExcelList 結(jié)果excel表
     * @param filePath        文件路徑
     * @author reshui
     * @date 2023/02/15
     */
    public static void outputExcelToLocal(String timeStamp, String excelFileName, Class headClassType, List resultExcelList, String filePath) {
        //文件時(shí)間戳
        timeStamp = Objects.nonNull(timeStamp) ? timeStamp : StrUtil.EMPTY;
        String partFileName = filePath + File.separator + excelFileName + separatorChar + timeStamp + "-log.xlsx";
        FileUtil.touch(partFileName);
        EasyExcel.write(partFileName, headClassType).sheet("源數(shù)據(jù)").doWrite(resultExcelList);
    }

    /**
     * 簡單把excel
     *
     * @param excelFileName   excel文件名字
     * @param headClassType   頭類類型
     * @param resultExcelList 結(jié)果excel表
     * @param filePath        文件路徑
     * @author reshui
     * @date 2023/02/15
     */
    public static void easyOutputExcelToLocal(String excelFileName, Class headClassType, List resultExcelList, String filePath) {
        String timeStamp = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        outputExcelToLocal(timeStamp, excelFileName, headClassType, resultExcelList, filePath);
    }

    public static void main(String[] args) {

        String timeStamp = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        String titleTmpDirPath = FileUtil.getTmpDirPath() + File.separator + "test" + File.separator + timeStamp + File.separator;
        try {
            System.out.println("日志存儲(chǔ)地址-[" + titleTmpDirPath + "]");
            log.info("日志存儲(chǔ)[" + titleTmpDirPath + "]");
            String partFileName = titleTmpDirPath + timeStamp + "-log.xlsx";
            FileUtil.touch(partFileName);
            EasyExcel.write(partFileName, String.class).sheet("源數(shù)據(jù)").doWrite(null);
        } catch (Exception e) {
            log.error("日志存儲(chǔ)[" + titleTmpDirPath + "]" + "-error:", e);
        }
    }
}

四、運(yùn)行

@RestController
@RequestMapping("/check")
public class TestController {


    @RequestMapping(value = "/run1",method = {RequestMethod.GET})
    public void run1(HttpServletResponse response) throws IOException {
        List<DemoData> demoDataList = data1();
        List<WriteHandler> customMergeStrategies = Arrays.asList(
                new CustomMergeStrategy(demoDataList.stream().map(DemoData::getName).collect(Collectors.toList()), 1));
        DownloadExcelUtil.downloadFile(response,DemoData.class, JSONObject.toJSONString(demoDataList),"測試","頁1"
                , customMergeStrategies);
    }

    public static List<DemoData> data1(){
        List<DemoData> demoDataList = new ArrayList<>();
        DemoData demoData0 = new DemoData();
        demoData0.setId("0");
        demoData0.setName("hello0");
        demoDataList.add(demoData0);

        DemoData demoData1 = new DemoData();
        demoData1.setId("1");
        demoData1.setName("hello1");
        demoDataList.add(demoData1);

        DemoData demoData11 = new DemoData();
        demoData11.setId("1");
        demoData11.setName("hello1");
        demoDataList.add(demoData11);

        DemoData demoData2 = new DemoData();
        demoData2.setId("2");
        demoData2.setName("hello2");
        demoDataList.add(demoData2);
        return demoDataList;
    }
}

到了這里,關(guān)于easyExcel合并單元格導(dǎo)出的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Spring Boot集成EasyExcel實(shí)現(xiàn)excel導(dǎo)入導(dǎo)出操作

    Spring Boot集成EasyExcel實(shí)現(xiàn)excel導(dǎo)入導(dǎo)出操作

    Easy Excel 官網(wǎng) Java解析、生成Excel比較有名的框架有Apache poi、jxl。但他們都存在一個(gè)嚴(yán)重的問題就是非常的耗內(nèi)存,poi有一套SAX模式的API可以一定程度的解決一些內(nèi)存溢出的問題,但POI還是有一些缺陷,比如07版Excel解壓縮以及解壓后存儲(chǔ)都是在內(nèi)存中完成的,內(nèi)存消耗依然很

    2024年02月14日
    瀏覽(19)
  • Spring Boot 集成 EasyExcel 3.x 優(yōu)雅實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出

    Spring Boot 集成 EasyExcel 3.x 優(yōu)雅實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出

    本章節(jié)將介紹 Spring Boot 集成 EasyExcel(優(yōu)雅實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出)。 ?? Spring Boot 2.x 實(shí)踐案例(代碼倉庫) EasyExcel 是一個(gè)基于 Java 的、快速、簡潔、解決大文件內(nèi)存溢出的 Excel 處理工具。它能讓你在不用考慮性能、內(nèi)存的等因素的情況下,快速完成 Excel 的讀、寫等功能。 Ea

    2024年02月03日
    瀏覽(53)
  • java-EasyExcel導(dǎo)出excel設(shè)置單元格為文本格式(含代碼)

    java-EasyExcel導(dǎo)出excel設(shè)置單元格為文本格式(含代碼)

    java-EasyExcel導(dǎo)出excel設(shè)置單元格為文本格式(含代碼) 在使用EasyExcel導(dǎo)出excel模板時(shí)。我們會(huì)發(fā)現(xiàn)導(dǎo)出的日期和大長度數(shù)字都會(huì)自動(dòng)更換格式,不是文本格式。并且在空白單元格輸入日期也是格式有問題的,如下所示,可以看到當(dāng)輸入相同的日期時(shí),格式會(huì)變成自適應(yīng),不是文

    2023年04月15日
    瀏覽(24)
  • 【java】EasyPoi導(dǎo)出導(dǎo)入(合并單元格)
  • Java導(dǎo)出Excel并合并單元格

    Java導(dǎo)出Excel并合并單元格

    需求:需要在導(dǎo)出excel時(shí)合并指定的單元格 項(xiàng)目基于若伊框架二次開發(fā),本著能用現(xiàn)成的就不自己寫的原則,先是嘗試了@Excel注解中needMerge屬性 查了一圈別人的使用,大致是需要定義一個(gè)List集合,集合元素為對象,對象中的屬性標(biāo)注@Excel注解,并表明name屬性 照葫蘆畫瓢 查

    2024年01月19日
    瀏覽(46)
  • Java POI導(dǎo)出Excel時(shí),合并單元格沒有邊框的問題

    Java POI導(dǎo)出Excel時(shí),合并單元格沒有邊框的問題

    今天用POI導(dǎo)出Excel的時(shí)候,發(fā)現(xiàn)導(dǎo)出的單元格確少邊框,最后發(fā)現(xiàn)有2個(gè)方案可以解決。 CellRangeAddress的4個(gè)參數(shù)分別表示:起始行號,終止行號, 起始列號,終止列號

    2024年02月14日
    瀏覽(25)
  • EasyExcel合并單元格(同列相同數(shù)據(jù)合并)

    EasyExcel合并單元格(同列相同數(shù)據(jù)合并)

    合并后效果如下: 合并策略代碼: 使用: 主體代碼來自網(wǎng)絡(luò),按自己業(yè)務(wù)修改,支持多列相同數(shù)據(jù)合并。

    2024年02月12日
    瀏覽(17)
  • EasyExcel合并單元格

    EasyExcel合并單元格

    EasyExcel默認(rèn)情況下寫Excel是一行一行的,單元格不會(huì)自動(dòng)合并,現(xiàn)在需求是合并這幾列中相同的數(shù)據(jù) 開始自己也不想做過多改動(dòng)代碼,經(jīng)過閱讀EasyExce官方文檔和大量博客之后總結(jié)了一個(gè)通用的工具類,重寫接口中的merge方法,然后自己在寫入Excel的時(shí)候指定實(shí)體類屬性以及對

    2024年02月15日
    瀏覽(18)
  • easyexcel內(nèi)容追加與單元格合并

    easyexcel內(nèi)容追加與單元格合并

    ? ? 這里的需求是,如果表格不存在,則新建表格,并填入數(shù)據(jù),如果表格存在,那么就追加內(nèi)容,并且支持單元格合并。 ? ? 內(nèi)容追加,需要分兩種方式插入,第一種就是沒有表格,需要生成表頭,并且插入內(nèi)容,第二種就是已經(jīng)有了表格,這個(gè)表格作為模板并,不用設(shè)置

    2023年04月22日
    瀏覽(17)
  • 【Spring Boot】SpringBoot 單元測試

    【Spring Boot】SpringBoot 單元測試

    單元測試(unit testing),是指對軟件中的最?可測試單元進(jìn)?檢查和驗(yàn)證的過程就叫單元測試。 1、可以?常簡單、直觀、快速的測試某?個(gè)功能是否正確。 2、使?單元測試可以幫我們在打包的時(shí)候,發(fā)現(xiàn)?些問題,因?yàn)樵诖虬埃缘膯卧獪y試必須通過,否則不能打包

    2024年02月07日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包