直接上代码
工具类
package com.ruoyi.common.utils.poi;
import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excels;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.dto.ExcelExportDto;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.reflect.ReflectUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
/**
* @BelongsPackage: com.ruoyi.common.utils.poi
* @Author: zjt
* @CreateTime: 2024-02-27 11:03
* @Description: TODO
* @Version: 1.0
*/
public class MultiExcellUtil {
private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
//表头
public List<Object[]> fields;
public static List<Object> importExcel(String sheetName, InputStream is, Class clazz) throws Exception {
List<Object> list = new ArrayList<Object>();
Workbook workbook = WorkbookFactory.create(is);
Sheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
throw new IOException("文件sheet不存在");
}
int rows = sheet.getPhysicalNumberOfRows();
if (rows > 0) {
// 定义一个map用于存放excel列的序号和field.
Map<String, Integer> cellMap = new HashMap<String, Integer>();
Row heard = sheet.getRow(0);
for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
Cell cell = heard.getCell(i);
if (StringUtils.isNotNull(cell)) {
String value = cell.getStringCellValue();
cellMap.put(value, i);
} else {
cellMap.put(null, i);
}
}
Field[] allFields = clazz.getDeclaredFields();
// 定义一个Map用于存放列的序号和field
Map<Integer, Field> fieldsMap = new HashMap<>();
for (int col = 0; col < allFields.length; col++) {
Field field = allFields[col];
Excel attr = field.getAnnotation(Excel.class);
if (attr != null) {
// 设置类的私有字段属性可访问.
field.setAccessible(true);
Integer column = cellMap.get(attr.name());
if (column != null) {
fieldsMap.put(column, field);
}
}
}
for (int i = 1; i < rows; i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
Object entity = null;
for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()) {
Integer keyInt = entry.getKey();
if (StringUtils.isNull(keyInt)) {
System.out.println("--------------------");
continue;
}
Object val = getCellValue(row, entry.getKey());
// 如果不存在实例则新建.
entity = (entity == null ? clazz.newInstance() : entity);
// 从map中得到对应列的field.
Field field = fieldsMap.get(entry.getKey());
// 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType();
if (String.class == fieldType) {
String s = Convert.toStr(val);
if (StringUtils.endsWith(s, ".0")) {
val = StringUtils.substringBefore(s, ".0");
} else {
String dateFormat = field.getAnnotation(Excel.class).dateFormat();
if (StringUtils.isNotEmpty(dateFormat)) {
val = DateUtils.parseDateToStr(dateFormat, (Date) val);
} else {
val = Convert.toStr(val);
}
}
} else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))) {
val = Convert.toInt(val);
} else if (Long.TYPE == fieldType || Long.class == fieldType) {
val = Convert.toLong(val);
} else if (Double.TYPE == fieldType || Double.class == fieldType) {
val = Convert.toDouble(val);
} else if (Float.TYPE == fieldType || Float.class == fieldType) {
val = Convert.toFloat(val);
} else if (BigDecimal.class == fieldType) {
val = Convert.toBigDecimal(val);
} else if (Date.class == fieldType) {
if (val instanceof String) {
val = DateUtils.parseDate(val);
} else if (val instanceof Double) {
val = DateUtil.getJavaDate((Double) val);
}
} else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) {
val = Convert.toBool(val, false);
}
if (StringUtils.isNotNull(fieldType)) {
Excel attr = field.getAnnotation(Excel.class);
String propertyName = field.getName();
if (StringUtils.isNotEmpty(attr.targetAttr())) {
propertyName = field.getName() + "." + attr.targetAttr();
} else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
} else if (StringUtils.isNotEmpty(attr.dictType())) {
val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
}
ReflectUtils.invokeSetter(entity, propertyName, val);
}
}
list.add(entity);
}
}
return list;
}
/**
* 反向解析值字典值
*
* @param dictLabel 字典标签
* @param dictType 字典类型
* @param separator 分隔符
* @return 字典值
*/
public static String reverseDictByExp(String dictLabel, String dictType, String separator) {
return DictUtils.getDictValue(dictType, dictLabel, separator);
}
/**
* 反向解析值字典值
*
* @param dictValue 字典标签
* @param dictType 字典类型
* @param separator 分隔符
* @return 字典值
*/
public static String reverseDictValueByExp(String dictValue, String dictType, String separator) {
return DictUtils.getDictLabel(dictType, dictValue, separator);
}
/**
* 反向解析值 男=0,女=1,未知=2
*
* @param propertyValue 参数值
* @param converterExp 翻译注解
* @param separator 分隔符
* @return 解析后值
*/
public static String reverseByExp(String propertyValue, String converterExp, String separator) {
StringBuilder propertyString = new StringBuilder();
String[] convertSource = converterExp.split(",");
for (String item : convertSource) {
String[] itemArray = item.split("=");
if (StringUtils.containsAny(separator, propertyValue)) {
for (String value : propertyValue.split(separator)) {
if (itemArray[1].equals(value)) {
propertyString.append(itemArray[0] + separator);
break;
}
}
} else {
if (itemArray[1].equals(propertyValue)) {
return itemArray[0];
}
}
}
return StringUtils.stripEnd(propertyString.toString(), separator);
}
/**
* 获取单元格值
*
* @param row 获取的行
* @param column 获取单元格列号
* @return 单元格值
*/
public static Object getCellValue(Row row, int column) {
if (row == null) {
return row;
}
Object val = "";
try {
Cell cell = row.getCell(column);
if (StringUtils.isNotNull(cell)) {
if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) {
val = cell.getNumericCellValue();
if (DateUtil.isCellDateFormatted(cell)) {
val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
} else {
if ((Double) val % 1 != 0) {
val = new BigDecimal(val.toString());
} else {
val = new DecimalFormat("0").format(val);
}
}
} else if (cell.getCellType() == CellType.STRING) {
val = cell.getStringCellValue();
} else if (cell.getCellType() == CellType.BOOLEAN) {
val = cell.getBooleanCellValue();
} else if (cell.getCellType() == CellType.ERROR) {
val = cell.getErrorCellValue();
}
}
} catch (Exception e) {
return val;
}
return val;
}
/**
* Excel生成多个sheet页,但是注意单个sheet页的行数不能超过默认限制
*
* @param sheetNames
* @param rowNameMap
* @return
*/
public static AjaxResult exportExcel(List<String> sheetNames, Map<String, Class> rowNameMap, String fileName) {
Workbook workbook = new XSSFWorkbook();
if (CollectionUtil.isNotEmpty(sheetNames)) {
// 循环创建sheet页
for (String sheetName : sheetNames) {
Sheet sheet = workbook.createSheet(sheetName);
Row row = sheet.createRow(0);
//List<String> rowNameList = rowNameMap.get(sheetName);
/*Class clazz = rowNameMap.get(sheetName);
Field[] rowNameList = clazz.getDeclaredFields();
if (rowNameList != null && rowNameList.length > 0) {
for (int i = 0; i < rowNameList.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(createStyles(workbook).get("header"));
cell.setCellValue(rowNameList[i].toString());
//Excel excel = (Excel) os[1];
}
}*/
List<Object[]> fields = createExcelField(rowNameMap.get(sheetName));
int column = 0;
for(Object[] os : fields) {
Excel excel = (Excel) os[1];
createCell(workbook, sheet, excel, row, column++);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(getAbsoluteFile(fileName));
workbook.write(outputStream);
outputStream.close();
workbook.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return AjaxResult.success(fileName);
}
/**
* 创建单元格
*/
private static Cell createCell(Workbook workbook, Sheet sheet, Excel attr, Row row, int column) {
// 创建列
Cell cell = row.createCell(column);
// 写入列信息
cell.setCellValue(attr.name());
setDataValidation(sheet, attr, row, column);
cell.setCellStyle(createStyles(workbook).get("header"));
return cell;
}
/**
* 创建表格样式
*/
public static void setDataValidation(Sheet sheet, Excel attr, Row row, int column) {
if (attr.name().indexOf("注:") >= 0) {
sheet.setColumnWidth(column, 6000);
} else {
// 设置列宽
sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
}
// 如果设置了提示信息则鼠标放上去提示.
if (StringUtils.isNotEmpty(attr.prompt())) {
// 这里默认设了2-101列提示.
setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
}
// 如果设置了combo属性则本列只能选择不能输入
if (attr.combo().length > 0) {
// 这里默认设了2-101列只能选择不能输入.
setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
}
}
/**
* 设置 POI XSSFSheet 单元格提示
*
* @param sheet 表单
* @param promptTitle 提示标题
* @param promptContent 提示内容
* @param firstRow 开始行
* @param endRow 结束行
* @param firstCol 开始列
* @param endCol 结束列
*/
public static void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
int firstCol, int endCol) {
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
DataValidation dataValidation = helper.createValidation(constraint, regions);
dataValidation.createPromptBox(promptTitle, promptContent);
dataValidation.setShowPromptBox(true);
sheet.addValidationData(dataValidation);
}
/**
* 设置某些列的值只能输入预制的数据,显示下拉框.
*
* @param sheet 要设置的sheet.
* @param textlist 下拉框显示的内容
* @param firstRow 开始行
* @param endRow 结束行
* @param firstCol 开始列
* @param endCol 结束列
* @return 设置好的sheet.
*/
public static void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
DataValidationHelper helper = sheet.getDataValidationHelper();
// 加载下拉列表内容
DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
// 数据有效性对象
DataValidation dataValidation = helper.createValidation(constraint, regions);
// 处理Excel兼容性问题
if (dataValidation instanceof XSSFDataValidation) {
dataValidation.setSuppressDropDownArrow(true);
dataValidation.setShowErrorBox(true);
} else {
dataValidation.setSuppressDropDownArrow(false);
}
sheet.addValidationData(dataValidation);
}
private static List<Object[]> createExcelField(Class clazz) {
List<Object[]> fieldList = new ArrayList<>();
List<Field> tempFields = new ArrayList<>();
tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
for (Field field : tempFields) {
// 单注解
if (field.isAnnotationPresent(Excel.class)) {
fieldList.add(new Object[]{field, field.getAnnotation(Excel.class)});
}
// 多注解
if (field.isAnnotationPresent(Excels.class)) {
Excels attrs = field.getAnnotation(Excels.class);
Excel[] excels = attrs.value();
for (Excel excel : excels) {
fieldList.add(new Object[]{field, excel});
}
}
}
return fieldList;
}
public static String getAbsoluteFile(String fileName) {
String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
File desc = new File(downloadPath);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
return downloadPath;
}
private static 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);
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;
}
/**
* 多sheet页数据导出
* @param data 导出信息
* @param fileName 文件名
* @return
*/
public static AjaxResult manyDataExportExcel(List<ExcelExportDto> data, String fileName){
Workbook workbook = new XSSFWorkbook();
if (CollectionUtil.isNotEmpty(data)) {
// 循环创建sheet页
for (ExcelExportDto excelExportDto : data) {
//无数据是跳出循环
if(excelExportDto.getData()==null){
continue;
}
Sheet sheet = workbook.createSheet(excelExportDto.getSheetName());
Row row = sheet.createRow(0);
List<Object[]> fields = createExcelField(excelExportDto.getClazz());
int column = 0;
for(Object[] os : fields) {
Excel excel = (Excel) os[1];
createCell(workbook, sheet, excel, row, column++);
}
//需导入数据
List dataList=excelExportDto.getData();
//循环导入数据
for (int index=0;index<dataList.size();index++) {
//根据数据创建行
Row currentRow=sheet.createRow(index+1);
for (int i=0;i<fields.size();i++){
// 创建列
Cell cell = currentRow.createCell(i);
try {
//获取类字段下的字段值
Field field = (Field) fields.get(i)[0];
Excel excel = (Excel) fields.get(i)[1];
Field valueField=dataList.get(index).getClass().getDeclaredField(field.getName());
//将字段访问设为公有
valueField.setAccessible(true);
Object value=valueField.get(dataList.get(index));
//判断当前字段是否时间类型
if(Date.class.isAssignableFrom(field.getType())){
String dateFormat = field.getAnnotation(Excel.class).dateFormat();
//字段为时间类型并且数据不为空时转换数据类型
if (StringUtils.isNotEmpty(dateFormat) && !Objects.isNull(value)) {
value = DateUtils.parseDateToStr(dateFormat, (Date) value);
} else {
value = Convert.toStr(value);
}
}
//当前字段是否有dictType字段注解,有则转换数据
if(StringUtils.isNotEmpty(excel.dictType())){
String reverseValue=reverseDictValueByExp(Convert.toStr(value), excel.dictType(), excel.separator());
if(StringUtils.isNotEmpty(reverseValue)){
value=reverseValue;
}
}
// 写入列信息
cell.setCellValue(value==null?"":value.toString());
cell.setCellStyle(createStyles(workbook).get("data"));
setDataValidation(sheet, excel, currentRow, i);
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
//如果设了需合并列,则开始合并单元格
if(excelExportDto.getCells().length>0&&excelExportDto.getCells()!=null){
addCellRange(sheet,excelExportDto.getCells());
}
}
}
try {
fileName=UUID.randomUUID().toString() + "_" + fileName + ".xlsx";
FileOutputStream outputStream = new FileOutputStream(getAbsoluteFile(fileName));
workbook.write(outputStream);
outputStream.close();
workbook.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return AjaxResult.success(fileName);
}
/**
* 设置单元格合并
* @param sheet sheet
* @param index 需合并的下标数组
*/
private static void addCellRange(Sheet sheet, int[] index){
//核对指定列
for (Integer integer : index) {
//开始行
int startIndex=0;
//结束行
int endInex=0;
//数据
String value="";
//循环excel数据合并单元格
for (int i =0;i<sheet.getLastRowNum()+1;i++){
//获取当前单元格牛内容
String currentValue=sheet.getRow(i).getCell(integer).getStringCellValue();
//跳过表头并开始赋值
if(i==0){
value=currentValue;
continue;
}
//单元格内容不相同并且所在行不一样时合并单元格
if(!currentValue.equals(value)){
if(startIndex!=endInex){
CellRangeAddress cellAddresses=new CellRangeAddress(startIndex,endInex,integer,integer);
sheet.addMergedRegion(cellAddresses);
}
value=currentValue;
startIndex=i;
endInex=i;
}else{
endInex=i;
}
//核对最后一行内容相同则合并
if(sheet.getLastRowNum()==i){
if(value.equals(currentValue) && i!=startIndex){
CellRangeAddress cellAddresses=new CellRangeAddress(startIndex,sheet.getLastRowNum(),integer,integer);
sheet.addMergedRegion(cellAddresses);
}
}
}
}
}
/**
* 创建并填入单元格数据
*/
private static Cell createCell(Workbook workbook, Sheet sheet, Excel attr, Row row, int column,Field field) {
// 创建列
Cell cell = row.createCell(column);
// 写入列信息
cell.setCellValue(attr.name());
setDataValidation(sheet, attr, row, column);
cell.setCellStyle(createStyles(workbook).get("header"));
return cell;
}
}
测试案例
package com.ruoyi.common.utils.poi;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
* @BelongsPackage: com.ruoyi.common.utils.poi
* @Author: zjt
* @CreateTime: 2024-02-27 10:30
* @Description: TODO
* @Version: 1.0
*/
public class TestDemo {
public static void main(String[] args) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("竞赛组织情况");
Sheet sheet2 = workbook.createSheet("竞赛决赛情况");
// 写入数据到sheet1
Row row1 = sheet1.createRow(0);
Cell cell1 = row1.createCell(0);
cell1.setCellValue("hello");
Cell cell11 = row1.createCell(1);
cell11.setCellValue("word");
Row row2 = sheet2.createRow(0);
Cell cell2 = row2.createCell(0);
cell2.setCellValue("hello");
try {
FileOutputStream outputStream = new FileOutputStream("D:\\test.xlsx");
workbook.write(outputStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
看不懂的私聊