1、添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>xlsx-streamer</artifactId>
<version>2.1.0</version>
</dependency>
2、导出excel工具类
package com.shucha.deveiface.biz.utils;
import com.monitorjbl.xlsx.StreamingReader;
import com.sdy.common.model.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class ExcelUtil {
public static byte[] exportExcel(List<String> headList, List<Map<String, Object>> dataList, String xlsType) throws BizException {
byte[] bytes = null;
try (Workbook workbook = StringUtils.endsWithIgnoreCase(xlsType, "xlsx") ? new XSSFWorkbook() : new HSSFWorkbook();
ByteArrayOutputStream os = new ByteArrayOutputStream()) {
int size = 65530;
int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));
for (int i = 0; i < sheetCount; i++) {
Sheet sheet = workbook.createSheet("sheet" + i);
sheet.setDefaultColumnWidth(13);
int rowIndex = 0;
if (headList != null && headList.size() > 0) {
writerHeader(headList, sheet);
rowIndex++;
}
int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();
writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);
}
workbook.write(os);
bytes = os.toByteArray();
} catch (Exception e) {
throw new BizException("" + e);
}
return bytes;
}
public static void write(List<String> headList, List<Map<String, Object>> dataList, String xlsxPath, Integer size) throws BizException {
File file = new File(xlsxPath);
try (SXSSFWorkbook workbook = new SXSSFWorkbook();
FileOutputStream outputStream = new FileOutputStream(file)) {
int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));
for (int i = 0; i < sheetCount; i++) {
Sheet sheet = workbook.createSheet(i + "");
sheet.setDefaultColumnWidth(13);
int rowIndex = 0;
if (headList != null && headList.size() > 0) {
writerHeader(headList, sheet);
rowIndex++;
}
int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();
writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);
}
workbook.write(outputStream);
} catch (Exception e) {
log.error("", e);
throw new BizException("" + e);
}
}
public static List<Map<String, Object>> readExcel(File file, Integer size, Integer current) throws BizException {
try (InputStream is = new FileInputStream(file);
Workbook workbook = StreamingReader.builder()
.rowCacheSize(100)
.bufferSize(4096)
.open(is)) {
List<String> headerList = new ArrayList<>();
List<Map<String, Object>> dataList = new ArrayList<>();
for (Sheet sheet : workbook) {
log.info(sheet.getSheetName());
int start = (current * size) + 1;
int end = start + 10;
int i = 0;
for (Row row : sheet) {
if (i == 0) {
for (Cell cell : row) {
headerList.add(cell.getStringCellValue());
}
} else if (i > start && i <= end) {
Map<String, Object> map = new HashMap<>();
int j = 0;
for (Cell cell : row) {
map.put(headerList.get(j), cell.getStringCellValue());
j++;
}
dataList.add(map);
} else if (i > end) {
break;
}
i++;
}
}
return dataList;
} catch (Exception e) {
log.error("", e);
throw new BizException("" + e);
}
}
List<String> headList = new ArrayList<>();
List<Map<String, Object>> dataList = new ArrayList<>();
headList.add("name");
headList.add("value");
for (int a = 0; a < 70000; a++) {
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "测试name" + a);
map1.put("value", "测试value" + a);
dataList.add(map1);
}
write(headList, dataList, "/opt/1111.xlsx", 500000);
List<Map<String, Object>> maps = readExcel(new File("D:/opt/1111.xlsx"), 10, 50);
maps.size();
return new int[]{190, 28};
public static byte[] exportExcelHead(List<String> headList, String xlsType) throws BizException {
byte[] bytes = null;
try (Workbook workbook = StringUtils.endsWithIgnoreCase(xlsType, "xlsx") ? new XSSFWorkbook() : new HSSFWorkbook();
ByteArrayOutputStream os = new ByteArrayOutputStream()) {
Sheet sheet = workbook.createSheet(0 + "");
sheet.setDefaultColumnWidth(13);
if (headList != null && headList.size() > 0) {
writerHeader(headList, sheet);
}
workbook.write(os);
bytes = os.toByteArray();
} catch (Exception e) {
throw new BizException("" + e);
}
return bytes;
}
public static void writerHeader(List<String> headList, Sheet sheet) {
Row row = sheet.createRow(0);
row.setHeightInPoints(21);
RichTextString text;
for (int i = 0; i < headList.size(); i++) {
Cell cell = row.createCell((short) i);
text = new XSSFRichTextString(headList.get(i));
cell.setCellValue(text.toString());
}
}
public static void writerData(List<Map<String, Object>> dataList, List<String> headList, Sheet sheet, int rowIndex) {
Row row;
Cell cell;
RichTextString text;
for (int i = 0; i < dataList.size(); i++) {
row = sheet.createRow(rowIndex + i);
Map<String, Object> datas = dataList.get(i);
for (int j = 0; j < headList.size(); j++) {
cell = row.createCell(j);
Object value = datas.get(headList.get(j));
String data = value == null ? "" : String.valueOf(value);
text = new XSSFRichTextString(data);
cell.setCellValue(text);
}
}
}
public static Object getValue(Cell cell) {
Object cellValue = "";
if (cell != null) {
switch (cell.getCellType()) {
case BOOLEAN:
cellValue = cell.getBooleanCellValue();
break;
case BLANK:
cellValue = cell.getBooleanCellValue();
break;
case ERROR:
cellValue = cell.getErrorCellValue();
break;
case NUMERIC:
cellValue = cell.getNumericCellValue();
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
}
} else {
cellValue = "";
}
return cellValue;
}
}
3、测试调用生成excel文件
@GetMapping("/template")
@ApiOperation(value = "动态生成excel模板")
public void templateDerive(HttpServletResponse response) throws BizException {
List<String> paramList = new ArrayList<>();
for (int i=0;i<5;i++) {
paramList.add("标题名称"+ i);
}
try {
byte[] bytes = ExcelUtil.exportExcelHead(paramList, "xlsx");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("utf-8");
String filename = "动态导出模板.xlsx";
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.getOutputStream().write(bytes);
} catch (Exception e) {
throw new BizException("模板文件生成失败!原因:" + e);
}
}
@GetMapping("/templateExcelData")
@ApiOperation(value = "导出模板和数据")
public void templateExcelData(HttpServletResponse response) throws BizException {
List<String> headList = new ArrayList<>();
List<Map<String, Object>> dataList = new ArrayList<>();
headList.add("name");
headList.add("value");
for (int a = 0; a < 50; a++) {
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "测试name" + a);
map1.put("value", "测试value" + a);
dataList.add(map1);
}
try {
byte[] bytes = ExcelUtil.exportExcel(headList, dataList, "xlsx");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("utf-8");
String filename = "动态导出模板和数据.xlsx";
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.getOutputStream().write(bytes);
} catch (Exception e) {
throw new BizException("模板文件生成失败!原因:" + e);
}
}