Spring java excel_SpringBoot之导入导出Excel(Java8实现)

本文介绍了如何在SpringBoot应用中利用Java8和Apache POI库实现Excel的导入导出功能。详细讲解了添加依赖、自定义实体类、创建ExcelUtils工具类以及在Controller层的实现,包括读取和写入Excel的操作。文中还提供了性能测试结果,展示了不同数据量下导出和读取的时间成本。
摘要由CSDN通过智能技术生成

1.添加springBoot支持

org.apache.poi

poi

3.13

org.apache.poi

poi-ooxml

3.13

2.自定义实体类所需要的bean

ExcelColumn

@Target({ElementType.FIELD})

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface ExcelColumn {

String value() default "";

int col() default 0;

}

3.ExcelUtils编写

import org.apache.commons.collections.CollectionUtils;

import org.apache.commons.lang3.BooleanUtils;

import org.apache.commons.lang3.CharUtils;

import org.apache.commons.lang3.StringUtils;

import org.apache.commons.lang3.math.NumberUtils;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.http.MediaType;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.math.BigDecimal;

import java.net.URLEncoder;

import java.util.*;

import java.util.concurrent.atomic.AtomicInteger;

import java.util.stream.Collectors;

import java.util.stream.Stream;

/**

* @author Abbot

* @description

* @date 2018/9/12 15:27

**/

public class ExcelUtils {

private final static Logger log = LoggerFactory.getLogger(ExcelUtils.class);

private final static String EXCEL2003 = "xls";

private final static String EXCEL2007 = "xlsx";

public static List readExcel(String path, Class cls,MultipartFile file){

String fileName = file.getOriginalFilename();

if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {

log.error("上传文件格式不正确");

}

List dataList = new ArrayList<>();

Workbook workbook = null;

try {

InputStream is = file.getInputStream();

if (fileName.endsWith(EXCEL2007)) {

// FileInputStream is = new FileInputStream(new File(path));

workbook = new XSSFWorkbook(is);

}

if (fileName.endsWith(EXCEL2003)) {

// FileInputStream is = new FileInputStream(new File(path));

workbook = new HSSFWorkbook(is);

}

if (workbook != null) {

//类映射 注解 value-->bean columns

Map> classMap = new HashMap<>();

List fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList());

fields.forEach(

field -> {

ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);

if (annotation != null) {

String value = annotation.valu

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值