基于 Java 的 Excel 导出类。数据源为 Map 结构
package cn.com.trs.event.core.utils.excelUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @moduleName: ExcelUtil
* @description: excel表格操作
* @author: 杨睿
* @date: 2022/12/30 10:05
**/
public class ExcelUtil {
private static final Logger log = LoggerFactory.getLogger(cn.com.trs.common.utils.poi.ExcelUtil.class);
/**
* Excel sheet最大行数,默认65536
*/
public static final int sheetSize = 65536;
/**
* 工作表名称
*/
private String sheetName;
/**
* 工作薄对象
*/
private Workbook wb;
/**
* 工作表对象
*/
private Sheet sheet;
/**
* 样式列表
*/
private Map<String, CellStyle> styles;
/**
* 导入导出数据列表
*/
private List<Map<String, Object>> list;
/**
* 列名
*/
private List<String> fields;
public void init (List<Map<String, Object>> list, String sheetName) {
if (list == null) {
list = new ArrayList<>();
}
this.list = list;
this.sheetName = sheetName;
this.fields = createExcelField();
createWorkbook();
}
/**
* 获取列名
*/
public List<String> createExcelField () {
List<String> fields = new ArrayList<>();
Map<String, Object> map = this.list.get(0);
map.forEach((k, v) -> {
fields.add(k);
});
return fields;
}
/**
* 创建一个工作簿
*/
public void createWorkbook () {
this.wb = new SXSSFWorkbook(500);
this.sheet = wb.createSheet();
wb.setSheetName(0, sheetName);
this.styles = createStyles(wb);
}
/**
* 表格导出
*
* @param response HTTP返回对象
* @param data 数据
* @param sheetName 表名
*/
public void exportExcel (HttpServletResponse response, List<Map<String, Object>> data, String sheetName) {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
this.init(data, sheetName);
try {
writeSheet();
wb.write(response.getOutputStream());
} catch (Exception e) {
log.error("导出Excel异常{}", e.getMessage());
} finally {
IOUtils.closeQuietly(wb);
}
}
/**
* 创建写入数据到Sheet
*/
public void writeSheet () {
// 取出一共有多少个sheet.
int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
for (int index = 0; index < sheetNo; index++) {
createSheet(sheetNo, index);
// 产生一行
Row row = sheet.createRow(0);
int column = 0;
// 写入各个字段的列头名称
for (String field : this.fields) {
this.createCell(field, row, column++);
}
fillExcelData(index, row);
}
}
/**
* 创建工作表
*
* @param sheetNo sheet数量
* @param index 序号
*/
public void createSheet (int sheetNo, int index) {
// 设置工作表的名称.
if (sheetNo > 1 && index > 0) {
this.sheet = wb.createSheet();
wb.setSheetName(index, sheetName + index);
}
}
/**
* 创建表头单元格
*/
public Cell createCell (String field, Row row, int column) {
// 创建列
Cell cell = row.createCell(column);
// 写入列信息
cell.setCellValue(field);
cell.setCellStyle(styles.get("header"));
return cell;
}
/**
* 填充excel数据
*
* @param index 序号
* @param row 单元格行
*/
public void fillExcelData (int index, Row row) {
int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, list.size());
for (int i = startNo; i < endNo; i++) {
row = sheet.createRow(i + 1 - startNo);
// 得到导出对象.
Map<String, Object> line = list.get(i);
int column = 0;
for (String field : this.fields) {
Cell cell;
try {
// 设置行高
short maxHeight = 512;
row.setHeight(maxHeight);
// 创建cell
cell = row.createCell(column);
cell.setCellStyle(styles.get("data1"));
cell.setCellValue(line.get(field).toString());
} catch (Exception e) {
log.error("导出Excel失败:{}", e);
}
column++;
}
}
}
/**
* 创建表格样式
*
* @param wb 工作薄对象
* @return 样式列表
*/
private Map<String, CellStyle> createStyles (Workbook wb) {
// 写入各条记录,每条记录对应excel表中的一行
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
Font titleFont = wb.createFont();
titleFont.setFontName("Arial");
titleFont.setFontHeightInPoints((short) 16);
titleFont.setBold(true);
style.setFont(titleFont);
styles.put("title", style);
style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font dataFont = wb.createFont();
dataFont.setFontName("Arial");
dataFont.setFontHeightInPoints((short) 10);
style.setFont(dataFont);
styles.put("data", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font headerFont = wb.createFont();
headerFont.setFontName("Arial");
headerFont.setFontHeightInPoints((short) 10);
headerFont.setBold(true);
headerFont.setColor(IndexedColors.WHITE.getIndex());
style.setFont(headerFont);
styles.put("header", style);
style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
Font totalFont = wb.createFont();
totalFont.setFontName("Arial");
totalFont.setFontHeightInPoints((short) 10);
style.setFont(totalFont);
styles.put("total", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.LEFT);
styles.put("data1", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.CENTER);
styles.put("data2", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.RIGHT);
styles.put("data3", style);
return styles;
}
}