阿里出品,Excel 操作利器:easy-excel

 

最近在做excel數據導出時,發現了一款挺好用的excel處理開源框架:easy-excel,阿里巴巴出品,github上已有10.7K Star,整個使用下來比較突出的有兩點:

  • 容易上手,無論是註解還是api比較好用

  • 相比Apache poi,比較節約內存,避免內存溢出等問題。

下面以excel的數據導出的demo爲例,談談該框架的應用實踐

  1. 使用@ExcelProperty 可以指定excel列表的標題和順序,index用來指定寫入excel標題順序,通過該註解,實現對象與excel標題的映射。

  package com.model;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;

public class User extends BaseRowModel {

    /**
     * 用戶id
     */
    @ExcelProperty(value = "用戶id", index = 0)
    private String userId;

    /**
     * 年齡
     */
    @ExcelProperty(value = "年齡", index = 1)
    private String age;

    /**
     * 薪水
     */
    @ExcelProperty(value = "薪水", index = 2)
    private String salary;

    /**
     * 職業
     */
    @ExcelProperty(value = "職業", index = 3)
    private String profession;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSalary() {
        return salary;
    }

    public void setSalary(String salary) {
        this.salary = salary;
    }

    public String getProfession() {
        return profession;
    }

    public void setProfession(String profession) {
        this.profession = profession;
    }
}
  1. excel下載首先要設置好HttpServletResponse參數,指定文件名時注意編碼,以免出現中文亂碼。

  2. 服務端向客戶端遊覽器發送文件時,如果是瀏覽器支持的文件類型,一般會默認使用瀏覽器打開,比如txt、jpg等,會直接在瀏覽器中顯示,如果需要提示用戶保存,就要利用Content-Disposition進行一下處理,關鍵在於一定要加上attachment

response.setHeader("Content-Disposition", "attachment;filename=" + fileName+".xlsx");

4.完整代碼如下:

/**
 * Alipay.com Inc. Copyright (c) 2004-2019 All Rights Reserved.
 */
package com.controller;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.google.common.collect.Lists;
import com.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * excel下載
 */
@RestController
@RequestMapping("/user")
public class ExcelDownLoadController {

    private Logger logger = LoggerFactory.getLogger(ExcelDownLoadController.class);

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downLoadExcel(HttpServletResponse response) {

        try {
            this.setUpResponseAttributes(response);
            ByteArrayOutputStream stream = this.writeToExcel();
            this.writeToResponse(stream,response);
        } catch (Exception e) {
            logger.error("downLoadExcel error", e);
            throw new RuntimeException("下載excel異常");
        }
    }


    /**
     * 基於easyExcel框架,把數據寫入到excel
     *
     * @return
     */
    private ByteArrayOutputStream writeToExcel() {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ExcelWriter excelWriter = new ExcelWriter(byteArrayOutputStream, ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0, User.class);
        excelWriter.write(Lists.newArrayList(buildUserData()), sheet);
        excelWriter.finish();
        return byteArrayOutputStream;
    }

    /**
     * 針對excel下載,設置相關的HttpServletResponse屬性
     *
     * @param response
     */
    private void setUpResponseAttributes(HttpServletResponse response) throws UnsupportedEncodingException {

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("application/vnd.ms-excel");
        //解決中文亂碼問題
        String fileName = new String("用戶名單".getBytes("gbk"),"iso8859-1");
        // 設定輸出文件頭
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName+".xlsx");
    }

    /**
     * 將byteStream寫進response輸出流中
     *
     * @param byteStream excel字節流
     * @param response   返回結果
     * @throws IOException
     */
    private void writeToResponse(ByteArrayOutputStream byteStream, HttpServletResponse response) throws IOException {

        try {
            ServletOutputStream responseStream = response.getOutputStream();
            byteStream.writeTo(responseStream);
            responseStream.flush();
        } catch (Exception e) {
            logger.error("writeToResponse error", e);
            throw e;
        } finally {
            byteStream.close();
        }
    }

    /**
     * 構建一條用戶數據,用來測試
     *
     * @return
     */
    private User buildUserData() {

        User user = new User();
        user.setUserId("10241000");
        user.setAge("20");
        user.setProfession("學生");
        user.setSalary("2000");
        return user;
    }
}

5.excel下載效果

啓動服務後,http://127.0.0.1:8080/user/download 下載excel,效果如下圖所示

圖片

圖片

圖片

github開源地址: https://github.com/alibaba/easyexcel

 

更多內容歡迎關注個人微信公衆號,一起成長!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章