使用easypoi将数据导入excel中

本文介绍如何使用easypoi将数据当如到excel中;
官方文档:http://easypoi.mydoc.io/
里面有介绍easypoi的注解使用等。
poi的依赖

 <!--easypoi的依赖-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.2.0</version>
        </dependency>

本文是将用户名和密码导入到excel中,所以封装一个用户对象

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * @program: bootshirojwt
 * @description:
 * @author: liu.chuanjiang
 * @create: 2022-05-11 20:55
 */
@Builder
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class UserInfo implements Serializable {
    private static final long serialVersionUID = 1L;
    @Excel(name = "用户名", width = 20, orderNum = "1")
    private String userName;
    @Excel(name = "密码", width = 20, orderNum = "2")
    private String password;


}

如果需要对excel的样式进行设置,那么就封装一个样式类

import cn.afterturn.easypoi.excel.export.styler.AbstractExcelExportStyler;
import cn.afterturn.easypoi.excel.export.styler.IExcelExportStyler;
import org.apache.poi.ss.usermodel.*;

/**
 * @ClassName: ExcelExportMyStylerImpl
 * @Description: 自定义报表导出样式,可以修改表头颜色,高度等
 * @Author: sunt
 * @Date: 2019/8/29 21:39
 * @Version 1.0
 **/
public class ExcelExportMyStyler extends AbstractExcelExportStyler implements IExcelExportStyler {

    public ExcelExportMyStyler(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;
    }
}

接下就是excel导出的核心之处了,excel工具类

package com.lcj.easypoi;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

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

/**
 * @ClassName: ExcelExportUtil
 * @Description: Exceld导出工具类
 * @Author: sunt
 * @Date: 2019/8/30 14:49
 * @Version 1.0
 **/
@Slf4j
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) {
        log.info("进入到exportExcel");
        ExportParams params = new ExportParams(headTitle, sheetName);
        params.setHeight((short) 8);
        params.setStyle(ExcelExportMyStyler.class);
        try {
            Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, listData);
            String fileName = headTitle + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            fileName = URLEncoder.encode(fileName, "UTF8");
            response.setCharacterEncoding("UTF-8");
            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();
        }
    }

    public static void exportExcel1(Collection<?> listData, Class<?> pojoClass, String headTitle, String sheetName) {
        log.info("进入到exportExcel");
        FileOutputStream outStream=null;
        try {
            String fileName = "C:\\Users\\Administrator.DESKTOP-JMAFGHR\\Desktop\\工作\\test.xlsx";
            outStream = new FileOutputStream(fileName);
            ExportParams params = new ExportParams(headTitle, sheetName);
            params.setHeight((short) 8);
            params.setStyle(ExcelExportMyStyler.class);
            Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, listData);
            workbook.write(outStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

测试类

/**
 * @program: test_pay
 * @description:
 * @author: liu.chuanjiang
 * @create: 2022-05-11 22:19
 */
public class test {
    public static void main(String[] args) {
        List<UserInfo> list=new ArrayList<>();
        UserInfo userInfo1 = new UserInfo().setUserName("张三").setPassword("123");
        list.add(userInfo1);
        UserInfo userInfo2 = new UserInfo().setUserName("李四").setPassword("456");
        list.add(userInfo2);

        MyExcelExportUtil.exportExcel1(list,UserInfo.class,"用户信息","用户号信息");
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Vue使用EasyPoi导入Excel文件,需要进行以下步骤: 1. 安装EasyPoi 在Vue项目使用EasyPoi需要先安装EasyPoi,可以通过npm进行安装: ``` npm install easypoi --save ``` 2. 创建Excel文件上传组件 在Vue项目创建一个Excel文件上传组件,可以使用第三方组件库如ElementUI或者自己编写组件。 3. 实现Excel文件上传功能 在Excel文件上传组件实现文件上传功能,并在上传成功后调用EasyPoi导入方法将Excel文件数据导入到Vue项目。示例代码如下: ```javascript import { importExcel } from 'easypoi'; export default { methods: { handleFileUpload(file) { importExcel(file.raw, { // 配置导入参数 }).then(data => { // 处理导入后的数据 }).catch(error => { // 处理导入失败的情况 }); } } } ``` 在上述代码,`handleFileUpload`方法表示文件上传成功后的回调函数,其`importExcel`方法是EasyPoi提供的导入Excel文件的方法,它接受两个参数:Excel文件数据导入参数。导入成功后,可以对导入数据进行处理。 4. 配置导入参数 在导入Excel文件时,可以配置一些参数来控制导入的过程,如表头行数、数据行数、数据类型等。示例代码如下: ```javascript import { importExcel } from 'easypoi'; export default { methods: { handleFileUpload(file) { importExcel(file.raw, { // 配置导入参数 titleRows: 1, // 表头行数,默认为1 startRows: 2, // 数据行开始行数,默认为2 type: 'array' // 导入数据类型,默认为array }).then(data => { // 处理导入后的数据 }).catch(error => { // 处理导入失败的情况 }); } } } ``` 在上述代码,`titleRows`表示表头的行数,默认为1;`startRows`表示数据行的开始行数,默认为2;`type`表示导入数据的类型,默认为array。 5. 处理导入后的数据导入Excel文件后,可以对导入数据进行处理。如将数据存储到数据、显示到页面上等。示例代码如下: ```javascript import { importExcel } from 'easypoi'; export default { data() { return { tableData: [] // 表格数据 } }, methods: { handleFileUpload(file) { importExcel(file.raw, { // 配置导入参数 }).then(data => { // 处理导入后的数据 this.tableData = data; }).catch(error => { // 处理导入失败的情况 }); } } } ``` 在上述代码,`tableData`是Vue组件用来存储导入后的数据的数组,当导入成功后,将数据存储到该数组,然后可以在页面上显示出来。 这就是在Vue使用EasyPoi导入Excel文件的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值