Java 使用EasyExcel導出工具類(實體類,非實體類,List<Map<String,Object>>)


〇:工具類內容

1.先引用pom.xml

     <dependency>
       <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.66</version>
      <scope>compile</scope>
     </dependency>
<!--阿里巴巴導出 easyexcel jar-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.6</version>
        </dependency>

 

2、定義兩個實體類

自行自動生成get,set方法

public class NoModelWriteData implements Serializable {
    private String fileName;//文件名
    private String[] headMap;//表頭數組
    private String[] dataStrMap;//對應數據字段數組
    private List<Map<String, Object>> dataList;//數據集合
}
public class SimpleWriteData implements Serializable {
    private String fileName;//文件名
    private List<?> dataList;//數據列表
}

3、添加工具類內容

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.google.common.net.HttpHeaders;
import com.roc.common.model.NoModelWriteData;
import com.roc.common.model.SimpleWriteData;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.RequestBody;

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

public class EasyExcelUtils {

    //不創建對象的導出
    public void noModleWrite(@RequestBody NoModelWriteData data, HttpServletResponse response) throws IOException {
        // 這里注意 有同學反應使用swagger 會導致各種問題,請直接用瀏覽器或者用postman
        try {
//            response.setContentType("application/vnd.ms-excel");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 這里URLEncoder.encode可以防止中文亂碼 當然和easyexcel沒有關系
            String fileName = URLEncoder.encode(data.getFileName(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 這里需要設置不關閉流
            EasyExcel.write(response.getOutputStream()).head(head(data.getHeadMap())).sheet(data.getFileName()).doWrite(dataList(data.getDataList(), data.getDataStrMap()));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下載文件失敗" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    //創建對象的導出
    public <T> void simpleWrite(@RequestBody SimpleWriteData data,Class<T> clazz, HttpServletResponse response) throws IOException {
        // 這里注意 有同學反應使用swagger 會導致各種問題,請直接用瀏覽器或者用postman
//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 這里URLEncoder.encode可以防止中文亂碼 當然和easyexcel沒有關系
        String fileName = URLEncoder.encode(data.getFileName(), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(data.getFileName()).doWrite(data.getDataList());
    }

    //設置表頭
    private List<List<String>> head(String[] headMap) {
        List<List<String>> list = new ArrayList<List<String>>();

        for (String head : headMap) {
            List<String> headList = new ArrayList<String>();
            headList.add(head);
            list.add(headList);
        }
        return list;
    }

    //設置導出的數據內容
    private List<List<Object>> dataList(List<Map<String, Object>> dataList, String[] dataStrMap) {
        List<List<Object>> list = new ArrayList<List<Object>>();
        for (Map<String, Object> map : dataList) {
            List<Object> data = new ArrayList<Object>();
            for (int i = 0; i < dataStrMap.length; i++) {
                data.add(map.get(dataStrMap[i]));
            }
            list.add(data);
        }
        return list;
    }
}

一:不使用實體類導出

這里只針對接口返回的List<Map<String,Object>>類型數據做后續操作,跟隨文章的步驟操作即可

1、查詢數據

如圖獲取了List<Map<String, Object>>類型的數據

 

 

 

2、定義數組

headMap數組定義的是導出文件表頭標題的內容,要按順序定義
dataStrMap數據定義的是標題對應的字段名(一定要按順序對應)

String[] headMap = { "項目名稱", "樓棟名稱", "單元名稱", "樓層名稱", "房間名稱", "業主/租戶姓名", "房間狀態", "房間功能","認證人數" };
String[] dataStrMap={"hName","bName","uName","fName","pName","cName","pState","pFunction","pNum"};

3、將數據放入工具類方法的實體類中

NoModelWriteData d = new NoModelWriteData();
d.setFileName("認證統計");
d.setHeadMap(headMap);
d.setDataStrMap(dataStrMap);
d.setDataList(listDatas);
EasyExcelUtils easyExcelUtils = new EasyExcelUtils();
easyExcelUtils.noModleWrite(d, response);

二:使用實體類導出

1、定義數據實體類

自行自動生成get,set方法,這里就不放出來了
實體類中的注解可以根據自己的需求使用,更多注解可查看文章開頭的官方示例文檔

@Data
public class PayInfoBillListExportDto implements Serializable {
    @ExcelProperty("項目名稱")
    private String hName;
    @ExcelProperty("樓棟名稱")
    private String bName;
    @ExcelProperty("單元名稱")
    private String uName;
    @ExcelProperty("樓層名稱")
    private String fName;
    @ExcelProperty("房間名稱")
    private BigDecimal pName;
    @ExcelProperty("業主/租戶姓名")
    private BigDecimal cName;
    @ExcelProperty("房間狀態")
    private BigDecimal pState;
    @ExcelProperty("房間功能")
    private BigDecimal pFunction;
    @ExcelProperty("認證人數")
    private String pNum;

//    @ExcelIgnore    此注解表示忽略這個字段
//    @DateTimeFormat("yyyy年MM月dd日HH時mm分ss秒")  時間格式化注解
//    @NumberFormat("#.##%")  百分比表示
//    @ColumnWidth(50)   設置單元格寬度為50
//    @ExcelProperty(value = "標題", index = 0)   第0列為標題列
}

1、查詢數據

 

 

 

 

2、將數據放入工具類方法的實體類中

SimpleWriteData d = new SimpleWriteData();
d.setFileName("認證統計");
d.setDataList(list);
EasyExcelUtils easyExcelUtils = new EasyExcelUtils();
easyExcelUtils.simpleWrite(d,PayInfoBillListExportDto.class,response);

此工具類只針對這兩種數據進行封裝

 

補充

但是在任務過程中,生成的文檔的格式要求並不符合產品和測試的期望值:如圖

 

 

 

 經過百度工程師的各種挑戰實驗和查閱實現了此功能

Excel文檔的自動列寬設置

//Excel文檔的自動列寬設置
public class ExcelWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
    private static final int MAX_COLUMN_WIDTH = 255;
    //因為在自動列寬的過程中,有些設置地方讓列寬顯得緊湊,所以做出了個判斷
    private static final int COLUMN_WIDTH = 2;
    private  Map<Integer, Map<Integer, Integer>> CACHE = new HashMap(8);


    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap = (Map)CACHE.get(writeSheetHolder.getSheetNo());
            if (maxColumnWidthMap == null) {
                maxColumnWidthMap = new HashMap(16);
                CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
            }

            Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
            if (columnWidth >= 0) {
                if (columnWidth > MAX_COLUMN_WIDTH) {
                    columnWidth = MAX_COLUMN_WIDTH;
                }else {
                    if(columnWidth<COLUMN_WIDTH){
                        columnWidth =columnWidth*2;
                    }
                }

                Integer maxColumnWidth = (Integer)((Map)maxColumnWidthMap).get(cell.getColumnIndex());
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    ((Map)maxColumnWidthMap).put(cell.getColumnIndex(), columnWidth);
                    writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(),  columnWidth* 256);
                }
            }
        }
    }

    private  Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        } else {
            CellData cellData = (CellData)cellDataList.get(0);
            CellDataTypeEnum type = cellData.getType();
            if (type == null) {
                return -1;
            } else {
                switch(type) {
                    case STRING:
                        return cellData.getStringValue().getBytes().length;
                    case BOOLEAN:
                        return cellData.getBooleanValue().toString().getBytes().length;
                    case NUMBER:
                        return cellData.getNumberValue().toString().getBytes().length;
                    default:
                        return -1;
                }
            }
        }
    }
//Excel的字體,樣式,背景色的設置
public static HorizontalCellStyleStrategy getStyleStrategy(){
// 頭的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 背景設置為灰色
headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
WriteFont headWriteFont = new WriteFont();
// 字體樣式
headWriteFont.setFontName("Frozen");
headWriteFont.setFontHeightInPoints((short)12);
headWriteFont.setBold(true);
headWriteCellStyle.setWriteFont(headWriteFont);
//自動換行
headWriteCellStyle.setWrapped(false);
// 水平對齊方式
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 垂直對齊方式
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

// 內容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 這里需要指定 FillPatternType 為FillPatternType.SOLID_FOREGROUND 不然無法顯示背景顏色.頭默認了 FillPatternType所以可以不指定
// contentWriteCellStyle.setFillPatternType(FillPatternType.SQUARES);
// 背景白色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
WriteFont contentWriteFont = new WriteFont();
// 字體大小
contentWriteFont.setFontHeightInPoints((short)12);
// 字體樣式
contentWriteFont.setFontName("Calibri");
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 這個策略是 頭是頭的樣式 內容是內容的樣式 其他的策略可以自己實現
return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
}
}

調用方式

這部分是因為我的Excel都是自定義開頭數據,所以用的是List<Map<String, Object>>

 EasyExcel.write(response.getOutputStream())
                    .head(head(data.getHeadMap()))
                    .registerWriteHandler(new ExcelWidthStyleStrategy())
                    .registerWriteHandler(ExcelWidthStyleStrategy.getStyleStrategy())
                    .sheet(data.getFileName())
                    .doWrite(dataList(data.getDataList()
                     ,data.getDataStrMap()));

下面部分是用上實體類的調用

 EasyExcel.write(outputStream).needHead(true)
                .head(clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .registerWriteHandler(new Custemhandler())
                .registerWriteHandler(EasyExcelUtil.getStyleStrategy())
                .sheet(0, sheetName)
                .doWrite(writeList);

修改后

工具類內容

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.dd2007.property.webapp.easyExcel.entity.NoModelWriteData;
import com.dd2007.property.webapp.easyExcel.entity.SimpleWriteData;
import com.sun.deploy.net.URLEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EasyExcelUtils {

    //不創建對象的導出
    public void noModleWrite(@RequestBody NoModelWriteData data, HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 這里URLEncoder.encode可以防止中文亂碼 當然和easyexcel沒有關系
            String fileName = URLEncoder.encode(data.getFileName(), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            EasyExcel.write(response.getOutputStream()).head(head(data.getHeadMap())).registerWriteHandler(new ExcelWidthStyleStrategy()).registerWriteHandler(ExcelWidthStyleStrategy.getStyleStrategy()).sheet(data.getFileName()).doWrite(dataList(data.getDataList(), data.getDataStrMap()));
        }catch (Exception e) {
        // 重置response
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        Map<String, String> map = new HashMap<String, String>();
        map.put("status", "failure");
        map.put("message", "下載文件失敗" + e.getMessage());
        response.getWriter().println(JSON.toJSONString(map));
        }
    }

    //創建對象的導出
    public <T> void simpleWrite(@RequestBody SimpleWriteData data, Class<T> clazz, HttpServletResponse response) throws IOException {
        // 這里注意 有同學反應使用swagger 會導致各種問題,請直接用瀏覽器或者用postman
//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 這里URLEncoder.encode可以防止中文亂碼 當然和easyexcel沒有關系
        String fileName = URLEncoder.encode(data.getFileName(), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(data.getFileName()).doWrite(data.getDataList());
    }

    //設置表頭
    private List<List<String>> head(String[] headMap) {
        List<List<String>> list = new ArrayList<List<String>>();
        for (String head : headMap) {
            List<String> headList = new ArrayList<String>();
            headList.add(head);
            list.add(headList);
        }
        return list;
    }

    //設置導出的數據內容
    private List<List<Object>> dataList(List<Map<String, Object>> dataList, String[] dataStrMap) {
        List<List<Object>> list = new ArrayList<List<Object>>();
        for (Map<String, Object> map : dataList) {
            List<Object> data = new ArrayList<Object>();
            for (int i = 0; i < dataStrMap.length; i++) {
                data.add(map.get(dataStrMap[i]));
            }
            list.add(data);
        }
        return list;
    }
}

 

參考說明:

如有疑問,可以參考以下文檔:

https://www.yuque.com/easyexcel/doc/easyexcel (EasyExcel 官網)

https://blog.csdn.net/weixin_44811578/article/details/107101248 (Excel文檔的字體,背景色,自動列寬的設置參考)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM