SpringBoot中怎么利用easyexcel導(dǎo)出Excel

今天就跟大家聊聊有關(guān)SpringBoot中怎么利用easyexcel導(dǎo)出Excel,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

網(wǎng)站的建設(shè)創(chuàng)新互聯(lián)建站專注網(wǎng)站定制,經(jīng)驗(yàn)豐富,不做模板,主營(yíng)網(wǎng)站定制開(kāi)發(fā).小程序定制開(kāi)發(fā),H5頁(yè)面制作!給你煥然一新的設(shè)計(jì)體驗(yàn)!已為成都塑料袋等企業(yè)提供專業(yè)服務(wù)。

首先我們創(chuàng)建一個(gè)springboot(版本是 2.1.4.RELEASE)項(xiàng)目,在此就不過(guò)多的啰嗦,創(chuàng)建好之后,首先需要引入easyexcel的maven坐標(biāo)。

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>easyexcel</artifactId>
  <version>1.1.2-beta5</version>
</dependency>

導(dǎo)入好了之后,我們接下來(lái)需要?jiǎng)?chuàng)建一個(gè)導(dǎo)出的模板類,首先要集成BaseRowModel,set、get省略,@ExcelProperty注解中的value就是表頭的信息,index是在第幾列,沒(méi)有加注解的不會(huì)導(dǎo)出。

public class OrderExcelBO extends BaseRowModel {

    @ExcelProperty(value = {"訂單ID"}, index = 0)
    private String id;

    /**
     * 訂單描述
     */
    @ExcelProperty(value = {"訂單描述"}, index = 2)
    private String description;

    /**
     * 訂單對(duì)應(yīng)產(chǎn)品id
     */
    @ExcelProperty(value = {"產(chǎn)品ID"}, index = 2)
    private Integer productId;

    /**
     * 支付方式描述,如:apple pay
     */
    @ExcelProperty(value = {"支付方式"}, index = 3)
    private String payMethod;

    /**
     * create_time
     */
    @ExcelProperty(value = {"時(shí)間"}, index = 4)
    private String createTime;

    /**
     * update_time
     */
    private String updateTime;

    /**
     * 產(chǎn)生訂單的用戶
     */
    @ExcelProperty(value = {"用戶ID"}, index = 5)
    private Integer userId;

    /**
     * 支付狀態(tài):0 未支付、1支付成功支付完成、-1支付失敗
     */
    @ExcelProperty(value = {"支付狀態(tài)"}, index = 6)
    private String status;

    /**
     * 訂單來(lái)源描述,如:ios 安卓
     */
    @ExcelProperty(value = {"手機(jī)型號(hào)"}, index = 7)
    private String platform;

    /**
     * 訂單流水
     */
    @ExcelProperty(value = {"訂單流水號(hào)"}, index = 8)
    private String flowNum;

    /**
     * 訂單金額
     */
    @ExcelProperty(value = {"金額"}, index = 9)
    private BigDecimal price;

    // @ExcelProperty(value = {"收據(jù)字段"}, index = 10)
    private String receipt;

    @ExcelProperty(value = {"APP來(lái)源"}, index = 10)
    private String sources;
}

導(dǎo)出的模板定義好之后,接下來(lái)就是一些封裝好的工具類的調(diào)用

  1. 查出我們需要導(dǎo)出的數(shù)據(jù);

  2. 生成Excel文件名和sheet名稱;

  3. 直接調(diào)用封裝好的工具類導(dǎo)出文件即可;

SpringBoot中怎么利用easyexcel導(dǎo)出Excel

我們來(lái)看下導(dǎo)出的效果SpringBoot中怎么利用easyexcel導(dǎo)出Excel

如果你的表頭比較復(fù)雜,那么根據(jù)需求,你也可自行定義,例如如下這種復(fù)雜的表頭,應(yīng)該如何設(shè)置SpringBoot中怎么利用easyexcel導(dǎo)出Excel

首先要修改模板類,如果合并的單元格最大為2,那么所有的表格都需要設(shè)置為2,不合并的單元格用空字符串填充,需要合并的單元格將合并部分寫(xiě)上相同的名稱,并且排列的序號(hào)要連續(xù),不能分開(kāi)。

SpringBoot中怎么利用easyexcel導(dǎo)出Excel

我們來(lái)看下導(dǎo)出的效果,這樣就可以滿足我們平時(shí)開(kāi)發(fā)需要的excel導(dǎo)出功能。簡(jiǎn)單易上手。

SpringBoot中怎么利用easyexcel導(dǎo)出Excel

工具類:

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

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

public class ExcelListener extends AnalysisEventListener {

   /**
    * 自定義用于暫時(shí)存儲(chǔ)data。
    * 可以通過(guò)實(shí)例獲取該值
    */
   private List<Object> datas = new ArrayList<>();

   /**
    * 通過(guò) AnalysisContext 對(duì)象還可以獲取當(dāng)前 sheet,當(dāng)前行等數(shù)據(jù)
    */
   @Override
   public void invoke(Object object, AnalysisContext context) {
      //數(shù)據(jù)存儲(chǔ)到list,供批量處理,或后續(xù)自己業(yè)務(wù)邏輯處理。
      datas.add(object);
      //根據(jù)業(yè)務(wù)自行 do something
      doSomething();
        /*
        如數(shù)據(jù)過(guò)大,可以進(jìn)行定量分批處理
        if(datas.size()<=100){
            datas.add(object);
        }else {
            doSomething();
            datas = new ArrayList<Object>();
        }
         */
   }

   /**
    * 根據(jù)業(yè)務(wù)自行實(shí)現(xiàn)該方法
    */
   private void doSomething() {
   }

   @Override
   public void doAfterAllAnalysed(AnalysisContext context) {
        /*
            datas.clear();
            解析結(jié)束銷(xiāo)毀不用的資源
         */
   }

   public List<Object> getDatas() {
      return datas;
   }

   public void setDatas(List<Object> datas) {
      this.datas = datas;
   }
}
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.mochu.exception.ExcelException;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class ExcelUtil {
    /**
     * 讀取 Excel(多個(gè) sheet)
     *
     * @param excel 文件
     * @param rowModel 實(shí)體類映射,繼承 BaseRowModel 類
     * @return Excel 數(shù)據(jù) list
     */
    public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel) {
        ExcelListener excelListener = new ExcelListener();
        ExcelReader reader = getReader(excel, excelListener);

        if (reader == null) {
            return null;
        }

        for (Sheet sheet : reader.getSheets()) {
            if (rowModel != null) {
                sheet.setClazz(rowModel.getClass());
            }
            reader.read(sheet);
        }

        return excelListener.getDatas();
    }

    /**
     * 讀取某個(gè) sheet 的 Excel
     *
     * @param excel 文件
     * @param rowModel 實(shí)體類映射,繼承 BaseRowModel 類
     * @param sheetNo sheet 的序號(hào) 從1開(kāi)始
     * @return Excel 數(shù)據(jù) list
     */
    public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo) {
        return readExcel(excel, rowModel, sheetNo, 1);
    }

    /**
     * 讀取某個(gè) sheet 的 Excel
     *
     * @param excel 文件
     * @param rowModel 實(shí)體類映射,繼承 BaseRowModel 類
     * @param sheetNo sheet 的序號(hào) 從1開(kāi)始
     * @param headLineNum 表頭行數(shù),默認(rèn)為1
     * @return Excel 數(shù)據(jù) list
     */
    public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo, int headLineNum) {
        ExcelListener excelListener = new ExcelListener();
        ExcelReader reader = getReader(excel, excelListener);

        if (reader == null) {
            return null;
        }

        reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass()));

        return excelListener.getDatas();
    }

    /**
     * 導(dǎo)出 Excel :一個(gè) sheet,帶表頭
     *
     * @param response HttpServletResponse
     * @param list 數(shù)據(jù) list,每個(gè)元素為一個(gè) BaseRowModel
     * @param fileName 導(dǎo)出的文件名
     * @param sheetName 導(dǎo)入文件的 sheet 名
     * @param object 映射實(shí)體類,Excel 模型
     */
    public static void writeExcel(HttpServletResponse response, List<? extends BaseRowModel> list, String fileName,
                                  String sheetName, BaseRowModel object) {
        ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0, object.getClass());
        sheet.setSheetName(sheetName);

        TableStyle tableStyle = new TableStyle();
        tableStyle.setTableContentBackGroundColor(IndexedColors.WHITE);
        Font font = new Font();
        font.setFontHeightInPoints((short) 9);
        tableStyle.setTableHeadFont(font);
        tableStyle.setTableContentFont(font);
        sheet.setTableStyle(tableStyle);

        writer.write(list, sheet);
        writer.finish();
    }

    /**
     * 導(dǎo)出 Excel :多個(gè) sheet,帶表頭
     *
     * @param response HttpServletResponse
     * @param list 數(shù)據(jù) list,每個(gè)元素為一個(gè) BaseRowModel
     * @param fileName 導(dǎo)出的文件名
     * @param sheetName 導(dǎo)入文件的 sheet 名
     * @param object 映射實(shí)體類,Excel 模型
     */
    public static ExcelWriterFactory writeExcelWithSheets(HttpServletResponse response,
                                                          List<? extends BaseRowModel> list, String fileName,
                                                          String sheetName, BaseRowModel object) {
        ExcelWriterFactory writer = new ExcelWriterFactory(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0, object.getClass());
        sheet.setSheetName(sheetName);
        sheet.setTableStyle(getTableStyle());
        writer.write(list, sheet);

        return writer;
    }

    /**
     * 導(dǎo)出融資還款情況表
     *
     * @param response
     * @param list
     * @param fileName
     * @param sheetName
     * @param object
     */
    public static void writeFinanceRepayment(HttpServletResponse response, List<? extends BaseRowModel> list,
                                             String fileName, String sheetName, BaseRowModel object) {
        ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0, object.getClass());
        sheet.setSheetName(sheetName);
        sheet.setTableStyle(getTableStyle());
        writer.write(list, sheet);

        for (int i = 1; i <= list.size(); i += 4) {
            writer.merge(i, i + 3, 0, 0);
            writer.merge(i, i + 3, 1, 1);
        }

        writer.finish();
    }

    /**
     * 導(dǎo)出文件時(shí)為Writer生成OutputStream
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
        //創(chuàng)建本地文件
        fileName = fileName + ".xls";

        try {
            fileName = new String(fileName.getBytes(), "ISO-8859-1");
            response.addHeader("Content-Disposition", "filename=">
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class ExcelWriterFactory extends ExcelWriter {
   private OutputStream outputStream;
   private int sheetNo = 1;

   public ExcelWriterFactory(OutputStream outputStream, ExcelTypeEnum typeEnum) {
      super(outputStream, typeEnum);
      this.outputStream = outputStream;
   }

   public ExcelWriterFactory write(List<? extends BaseRowModel> list, String sheetName, BaseRowModel object) {
      this.sheetNo++;
      try {
         Sheet sheet = new Sheet(sheetNo, 0, object.getClass());
         sheet.setSheetName(sheetName);
         this.write(list, sheet);
      }
      catch(Exception ex) {
         ex.printStackTrace();
         try {
            outputStream.flush();
         }
         catch(IOException e) {
            e.printStackTrace();
         }
      }
      return this;
   }

   @Override
   public void finish() {
      super.finish();
      try {
         outputStream.flush();
      }
      catch(IOException e) {
         e.printStackTrace();
      }
   }
}

看完上述內(nèi)容,你們對(duì)SpringBoot中怎么利用easyexcel導(dǎo)出Excel有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

分享名稱:SpringBoot中怎么利用easyexcel導(dǎo)出Excel
鏈接分享:http://www.muchs.cn/article32/jpjjsc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開(kāi)發(fā)、建站公司、手機(jī)網(wǎng)站建設(shè)、動(dòng)態(tài)網(wǎng)站、App開(kāi)發(fā)小程序開(kāi)發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都app開(kāi)發(fā)公司