org.yes.tools.utils.ExcelUtil Maven / Gradle / Ivy
package org.yes.tools.utils;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.yes.tools.core.exception.YesBaseException;
import org.yes.tools.listener.ExcelListener;
import org.yes.tools.strategy.ExcelCellWidthStyleStrategy;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
/***
* excel 工具类
*
* @author Co.
* @date: 2022/10/22 13:28
* @return
*/
@Slf4j
public class ExcelUtil {
/***
* 导出工具
*
* @author Co.
* @date: 2022/8/26 10:44
* @param list 数据
* @param head 导出的类
* @param fName 文件名
* @param sheet 标题
* @param converters 策略LISTS
* @return
*/
public static ResponseEntity exportExcel(List> list, Class head, String fName, String sheet, List converters) throws IOException {
String fileName = URLEncoder.encode(fName + DateUtil.today(), "UTF-8").replaceAll("\\+", "%20");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ExcelWriterBuilder write = EasyExcel.write(bos, head);
converters.forEach((item) -> {
write.registerConverter(item);
});
write.registerWriteHandler(new ExcelCellWidthStyleStrategy());
write.useDefaultStyle(true);
write.sheet(fName).doWrite(list);
byte[] bytes = bos.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf("application/vnd.ms-excel"));
headers.setContentDispositionFormData("attachment", fileName + ".xlsx");
return new ResponseEntity(bytes, headers, HttpStatus.CREATED);
}
/***
* 导入数据
*
* @author Co.
* @date: 2022/10/28 16:06
* @return
*/
public static List> importExcel(MultipartFile file, Class> clazz) {
if (file == null || file.isEmpty()) {
throw new RuntimeException("没有文件或者文件内容为空!");
}
List