spring boot +vue 导出excal之poi

爷,独闯天下 提交于 2020-08-14 10:58:00

java代码:

1、pom

<!-- poi-->
<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>

2、导出工具类ExportExcelUtils  注:其中一些背景色不显示可能是HSSFColor对xsl的兼容性问题  具体到什么包就不说了(pom引对应该都没问题)

package com.hsing.wooxabbs.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.hsing.wooxabbs.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author:xing.Li
 * @date:2020/3/9 19:57
 */
@Component
@Slf4j
public class ExportExcelUtils {
    private static Short Color_bg_White = HSSFColor.WHITE.index;

    public HSSFWorkbook expotr(List<User> list){
        //工作空间
        HSSFWorkbook workbook = new HSSFWorkbook();

        //1张工作表
        HSSFSheet sheet1 = workbook.createSheet("用户列表");
        sheet1.setDefaultRowHeightInPoints(25);//行高
        sheet1.setDefaultColumnWidth(25);//列宽
        //行标题//行表头
        setTitle( workbook,sheet1);
        //行数据体
        if (list.size()>0){
            list.forEach(WooUtils.consumerWithIndex((user, index) ->{
                HSSFRow bodyRow = null;
                bodyRow = sheet1.createRow(sheet1.getLastRowNum() + 1);
                bodyRow.createCell(0).setCellValue(index+1);
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getId());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getRealName());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getUserName());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getPassWord());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getPhone());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getEmailBox());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getAvatarColor());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getSex());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getIsLogin());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getIsDelete());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getIsActivation());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getIsDisable());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getCreateTime());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getUpdateTime());
                bodyRow.createCell(bodyRow.getLastCellNum()).setCellValue(user.getRoleName());
                bodyRow.setHeightInPoints(20);//设置row的行高
                for (int j = 0; j <bodyRow.getLastCellNum(); j++) {
                    bodyRow.getCell(j).setCellStyle(getBodyStyle(workbook,Color_bg_White,10));//tianlan  HSSFColor.SKY_BLUE.index
                }
            }));
        }
        return workbook ;
    }

    /***
     * 设置表头
     *
     * @param workbook
     * @param sheet
     */
    private void setTitle(HSSFWorkbook workbook, HSSFSheet sheet) {
        //行标题
        HSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("用户列表");
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,16));////合并单元格
        titleRow.setHeightInPoints(25);//设置row的行高
        titleRow.getCell(0).setCellStyle(getCellStyle(workbook,Color_bg_White,20));//tianlan  HSSFColor.SKY_BLUE.index
        //行表头
        sheet.setColumnWidth(0,256*10+184);
        HSSFRow headRow = sheet.createRow(sheet.getLastRowNum() + 1);
        headRow.setHeightInPoints(25);//设置row的行高
        headRow.createCell(0).setCellValue("序号");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("id");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("真实姓名");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("登录名");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("密码");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("电话");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("邮箱");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("邮箱颜色");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("性别 10");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("是否登录1登录");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("是否删除1存在");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("是否激活1激活");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("是否启用1启用");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("创建时间");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("修改时间");
        headRow.createCell(headRow.getLastCellNum()).setCellValue("角色权限");
        //行表头单元格设置样式
        for(int h = 0; h < headRow.getLastCellNum() ; h ++) {
            headRow.getCell(h).setCellStyle(getCellStyle(workbook,Color_bg_White,14));//huise   HSSFColor.GREY_25_PERCENT.index
        }
    }

    /**
     * 设置标题样式
     * @param workbook 工作空间
     * @return
     */
    public HSSFCellStyle getCellStyle(HSSFWorkbook workbook, short bg, int fontSize) {
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//单元格-垂直居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//单元格-水平居中

        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//背景色-方块填充
        cellStyle.setFillForegroundColor(bg);//前背景色
        cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);//后背景色-浅黄
        //设置边框
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.DASH_DOT_DOT);//左边框
        cellStyle.setBorderTop(BorderStyle.THIN);//上边框
        cellStyle.setBorderRight(BorderStyle.THIN);//右边框
        cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index);//底边框颜色-暗红

        //日期显示格式
        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m-d-yy h:mm:ss"));
        //设置自动换行
        cellStyle.setWrapText(true);
        //设置字体
        cellStyle.setFont(getFont(workbook,fontSize));
        return cellStyle;
    }

    public  HSSFCellStyle getBodyStyle(HSSFWorkbook workbook, short bg, int fontSize) {
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//单元格-垂直居中
        cellStyle.setAlignment(HorizontalAlignment.LEFT);//单元格-水平居左
        return cellStyle;
    }

    /**
     * 获取设置好的字体
     * @param workbook 工作空间  fontSize  字体大小
     * @return
     */
    public  HSSFFont getFont(HSSFWorkbook workbook, int fontSize) {
        HSSFFont fontStyle = workbook.createFont();
        fontStyle.setFontName("宋体");//名称-宋体
        fontStyle.setFontHeightInPoints((short)fontSize);//
        fontStyle.setColor(HSSFColor.BLACK.index);//颜色-白色
        fontStyle.setBold(true);

//        fontStyle.setItalic(true);//斜体
//        fontStyle.setUnderline(HSSFFont.U_SINGLE);//下划线
        return fontStyle;
    }
}

3.controller   

@PostMapping(value = "/userPort")
@ApiOperation(value = "导出用户",notes = "导出用户")
public void userPort(@RequestParam(value = "portType", required = false)Integer portType, HttpServletResponse response) {
    String fileName="用户模板";
    List<User> users = new ArrayList<>();
    if (portType == 0){
        fileName = LocalDate.now()+"用户列表";
        users = authService.getUserList();
    }
    OutputStream os = null;
    try {
        HSSFWorkbook workbook = exportExcelUtils.expotr(users);
        os = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls");
        workbook.write(os);
        os.flush();
    }catch (Exception e) {
        e.printStackTrace();
    }finally {
        if(os!=null){
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

vue代码:

1、按钮和点击触发   用的element ui(大多数的导出都是a标签或者是用from,个人感觉不太好就问了度娘)--具体来源找不到了,搜的太多原链接被清了

<el-button size="mini" class="el_user_btn user_portOut" @click="userExport">人员导出
  <i class="iconfont icon-daochu icon_font"></i></el-button>

2、触发函数  portType是一个对比值,传到后端判断是模板还是全数据(也就是个post请求)axios就不说怎么用了

userExportSub(portType){
  let { userPort } = url;
  axios({
    url: userPort,//获取文件流的接口路径
    method: 'post',
    data: qs.stringify({
      "portType": portType
    }),
    responseType: 'blob' // 表明返回服务器返回的数据类型 很重要!!
  }).then((res) => {
    //将文件流转成blob形式
    const blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
    let filename ='用户列表.xls';
    //创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
    const eLink = document.createElement('a');
    eLink.download = filename;
    eLink.style.display = 'none';
    eLink.href = URL.createObjectURL(blob);
    document.body.appendChild(eLink);
    eLink.click();
    URL.revokeObjectURL(eLink.href); // 释放URL 对象
    document.body.removeChild(eLink);
  }).catch(error => {
    this.$message.error('导出失败');

  })
},
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!