超級簡單POI導出Excel實戰


在一般的生產管理系統都會將數據通過頁面導出到Excel,這里以Java為例通過第三方開源poi進行對Excel的操作,具體操作如下

1.引入jar包依賴

這里我以maven的方式引入jar包,具體依賴如下

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>3.2.0</version>
</dependency>

2.創建自定義導出Excel樣式類

package com.sunny.spring.boot.poi.common;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;

import cn.afterturn.easypoi.excel.export.styler.AbstractExcelExportStyler;
import cn.afterturn.easypoi.excel.export.styler.IExcelExportStyler;
/**
 * @ClassName: ExcelExportMyStylerImpl
 * @Description: 自定義報表導出樣式,可以修改表頭顏色,高度等
 * @Author: sunt
 * @Date: 2019/8/29 21:39
 * @Version 1.0
 **/
public class ExcelExportMyStylerImpl extends AbstractExcelExportStyler implements IExcelExportStyler {

    public ExcelExportMyStylerImpl(Workbook workbook) {
        super.createStyles(workbook);
    }

    @Override
    public CellStyle getTitleStyle(short color) {
        CellStyle titleStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);// 加粗
        titleStyle.setFont(font);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);// 居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        titleStyle.setFillForegroundColor(IndexedColors.AQUA.index);// 設置顏色
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setWrapText(true);
        return titleStyle;
    }

    @SuppressWarnings("deprecation")
    @Override
    public CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setDataFormat(STRING_FORMAT);
        if (isWarp) {
            style.setWrapText(true);
        }
        return style;
    }

    @Override
    public CellStyle getHeaderStyle(short color) {
        CellStyle titleStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);// 加粗
        font.setColor(IndexedColors.RED.index);
        font.setFontHeightInPoints((short) 11);
        titleStyle.setFont(font);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);// 居中
        titleStyle.setFillForegroundColor(IndexedColors.WHITE.index);// 設置顏色
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setWrapText(true);
        return titleStyle;
    }

    @SuppressWarnings("deprecation")
    @Override
    public CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setDataFormat(STRING_FORMAT);
        if (isWarp) {
            style.setWrapText(true);
        }
        return style;
    }
}

3.創建核心導出工具類

(注:該類只需要傳遞導出的Excel的數據集合、導出對象實體Bean(具體下面詳細說明)、表頭名稱、sheet名稱)

package com.sunny.spring.boot.poi.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.sunny.spring.boot.poi.common.ExcelExportMyStylerImpl;
import com.sunny.spring.boot.poi.pojo.StudentInfoBean;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: ExcelExportUtil
 * @Description: Exceld導出工具類
 * @Author: sunt
 * @Date: 2019/8/30 14:49
 * @Version 1.0
 **/
public class MyExcelExportUtil {

    /**
     * Excel文件導出,導出的文件名默認為:headTitle+當前系統時間
     * @param listData 要導出的list數據
     * @param pojoClass 定義excel屬性信息
     * @param headTitle Excel文件頭信息
     * @param sheetName Excel文件sheet名稱
     * @param response
     */
    public static void exportExcel(Collection<?> listData,Class<?> pojoClass, String headTitle, String sheetName, HttpServletResponse response) {
        ExportParams params = new ExportParams(headTitle, sheetName);
        params.setHeight((short) 8);
        params.setStyle(ExcelExportMyStylerImpl.class);
        try {
            Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, listData);
            String fileName = headTitle + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            fileName = URLEncoder.encode(fileName, "UTF8");
            response.setContentType("application/vnd.ms-excel;chartset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName + ".xls");
            ServletOutputStream out=response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4.創建導出對象實體Bean

該對象主要作用指定導出到Excel列名稱、寬度、列排序等信息,先貼代碼嗎,這里以學生基本信息為案例說明

package com.sunny.spring.boot.poi.pojo;

import cn.afterturn.easypoi.excel.annotation.Excel;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * <p>
 * 學生基本信息表
 * </p>
 *
 * @author sunt
 * @since 2019-08-29
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("T_STUDENT")
public class StudentInfoBean implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 學號
     */
    @TableId("ID")
    @Excel(name = "學號", width = 20, orderNum = "1")
    private String id;

    /**
     * 姓名
     */
    @TableField("NAME")
    @Excel(name = "姓名", width = 20, orderNum = "2")
    private String name;

    /**
     * 性別(1:男 2:女)
     * replace:導出是{a_id,b_id} 導入反過來,注意大括號里面單獨引號引起來的
     */
    @TableField("SEX")
    @Excel(name = "性別", width = 20, replace = { "男_1", "女_2" },orderNum = "3")
    private String sex;

    /**
     * 年齡
     */
    @TableField("AGE")
    @Excel(name = "年齡", width = 20, orderNum = "4")
    private Integer age;

    /**
     * 出生日期
     */
    @TableField("BIRTHDAY")
    @Excel(name = "出生日期", width = 20, orderNum = "5")
    private String birthday;

    /**
     * 入學時間
     */
    @TableField("REGIST_DATE")
    @Excel(name = "入學時間",width = 20,orderNum = "6")
    private String registDate;

    /**
     * 學費
     */
    @TableField("FEE")
    @Excel(name = "學費", width = 20, orderNum = "7")
    private BigDecimal fee;


}
注解字段說明
屬性字段 屬性值
@TableField
這個字段代表數據庫表的字段
@Excel
 name代表導出Excel列名稱
 @Excel  orderNum代表Excel列排在第幾列
 @Excel  replace一般數據庫存的性別例如0和1,導出的值0展示為男性,女展示為女性

 

 

 

 

 

 

5.具體使用案例

這里我們點擊頁面導出按鈕將數據庫信息查詢出來導出到Excel

5.1.創建SQL腳本和初始化數據

CREATE TABLE `t_student` (
  `ID` varchar(20) NOT NULL COMMENT '學號',
  `NAME` varchar(20) NOT NULL COMMENT '姓名',
  `SEX` char(1) NOT NULL COMMENT '性別(1:男 2:女)',
  `AGE` int(3) NOT NULL COMMENT '年齡',
  `BIRTHDAY` datetime NOT NULL COMMENT '出生日期',
  `REGIST_DATE` datetime NOT NULL COMMENT '入學時間',
  `FEE` decimal(5,2) NOT NULL COMMENT '學費',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='學生基本信息表';
INSERT INTO `study`.`t_student` (`ID`, `NAME`, `SEX`, `AGE`, `BIRTHDAY`, `REGIST_DATE`, `FEE`) VALUES ('1', '張三', '1', '18', '2019-08-29 05:57:02', '2019-08-29 18:00:00', '199.12');
INSERT INTO `study`.`t_student` (`ID`, `NAME`, `SEX`, `AGE`, `BIRTHDAY`, `REGIST_DATE`, `FEE`) VALUES ('2', '小紅', '2', '16', '2019-08-29 19:03:03', '2019-08-29 00:00:00', '226.55');

5.2.寫一個查詢所有學生信息接口

這里不做限制,以自己項目所使用的技術實現查詢信息即可,這里只貼出接口代碼,具體實現按自己的業務場景進行實現

package com.sunny.spring.boot.poi.service;

import com.sunny.spring.boot.poi.pojo.StudentInfoBean;

import java.util.List;

/**
 * @ClassName: IStudentService
 * @Description: 學生基本信息接口
 * @Author: sunt
 * @Date: 2019/8/30 14:56
 * @Version 1.0
 **/
public interface IStudentService {

    /**
     * 查詢所有學生
     * @return
     */
    List<StudentInfoBean> queryAllStudent();
}

5.3.查詢學生基本信息返回數據格式

[
    {
        "id": "1",
        "name": "張三",
        "sex": "1",
        "age": 18,
        "birthday": "2019-08-29 05:57:02",
        "registDate": "2019-08-29 18:00:00",
        "fee": 199.12
    },
    {
        "id": "2",
        "name": "小紅",
        "sex": "2",
        "age": 16,
        "birthday": "2019-08-29 19:03:03",
        "registDate": "2019-08-29 00:00:00",
        "fee": 226.55
    }
]

5.4.導出Excel方法

其實這里是最核心也是最簡單的地方,只需要調用上一步查詢所有學生基本信息的接口獲取到數據然后再調用導出Excel工具類即可,具體實現如下

package com.sunny.spring.boot.poi.controller;

import com.sunny.spring.boot.poi.pojo.StudentInfoBean;
import com.sunny.spring.boot.poi.service.IStudentService;
import com.sunny.spring.boot.poi.util.MyExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName: StudentController
 * @Description: Excel導出測試
 * @Author: sunt
 * @Date: 2019/8/30 14:59
 * @Version 1.0
 **/
@Controller
@RequestMapping("/export")
public class ExcelExportController {

    @Autowired(required = false)
    private IStudentService studentService;
    
    @RequestMapping("/exportStudent")
    public void exportStudent(HttpServletResponse response) {
        try {
            List<StudentInfoBean> sutdentList = studentService.queryAllStudent();
            MyExcelExportUtil.exportExcel(sutdentList,StudentInfoBean.class,"學生基本信息","新生入學信息",response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5.5.通過頁面導出按鈕導出Excel

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="layui\css\layui.css" media="all">
    <!-- 注意:如果你直接復制所有代碼到本地,上述css路徑需要改成你本地的 -->
</head>
<body>
<form action="/export/exportStudent">
    <fieldset class="layui-elem-field site-demo-button" style="margin-top: 30px;">
        <legend>Excel導入導出</legend>
        <div>
            <button class="layui-btn" lay-submit="" lay-filter="studentForm">導出學生基本信息</button>
        </div>
    </fieldset>
</form>
</body>
</html>

6.導出展示

 

導出樣式展示

 

7.源代碼地址 

https://gitee.com/SunnySVN/SpringBoot-Study.git 歡迎各位大佬路過點個Star

注:poi多個sheet的導出以及合並單元格的方式導出,有需求的小伙伴可以在評論區留言,有時間我會更新


免責聲明!

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



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